问题描述
如何在 tableView 中设置这个 json。
{
"page":0,"pageSize":5,"totalPageCount":16,"wkda":{
"020":"Abarth","040":"Alfa Romeo","042":"Alpina","043":"Alpine","057":"Aston Martin"
}
}
解决方法
创建一个代表你的数据的结构
struct YourObjectName: Codable {
let page,pageSize,totalPageCount: Int
let wkda: [String: String]
}
从服务器获取数据时,将 json 解析为新创建的对象,并将该对象存储在 viewController 中的某个位置。
let yourObject = try? newJSONDecoder().decode(YourObjectName.self,from: jsonData)
在配置tableView时,根据你的数据设置行数:
func tableView(_ tableView: UITableView,numberOfRowsInSection section: Int) -> Int {
return yourObject.count // Or something similar,based on your needs
}
最后使用您的数据填充单元格:
override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SomeIdentifier",for: indexPath)
// Populate your cell
return cell
}
另外,我鼓励您阅读有关 TableView 的一些内容。这是一个很好的起点:TableViews