我是IOS应用程序开发的初学者,我想将JSON文件的所有键的值添加到tableView中。
我已经尝试了下面的代码,但是tableView仍然是空的。
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
var arraylist = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let session = URLSession.shared
let url = URL(string: "http://country.io/names.json")!
let task = session.dataTask(with: url) { data, response, error in
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: String] {
for (key, value) in json {
let someString = value
self.arraylist.append(someString)
}
}
} catch {
print("JSON error: \(error.localizedDescription)")
}
}
task.resume()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return(arraylist.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = arraylist[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
最佳答案
首先检查
表视图的datasource
和delegate
连接到界面生成器中的视图控制器。
原型单元的标识符设置为cell
。
为表视图添加IBOutlet
并在接口生成器中连接它
@IBOutlet weak var tableView : UITableView!
给数据源数组起一个更有意义、不那么委婉的名字
var countries = [String]()
填充数据源数组后,在主线程上重新加载表视图
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String] {
// easier way to get the country names
self.countries = json.values.sorted()
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
总是
dequeue
单元格public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = countries[indexPath.row]
return cell
}
return
不是函数(没有括号)return countries.count