我有一个名为itemInfo.json的本地JSON文件,其中包含一个字典,该字典包含将近6000个键值对,其中包含项名称和项ID。
{ "itemName1" : 2564,
"itemName2" : 470,
"itemName3" : 1849,
"itemName4" : 60,
"itemName5" : 103 }
// continues for a few thousand more
在将JSON文件加载到控制台中时,我没有问题,但是我不知道如何将项目名称打印到列表中的tableview上。列表中不需要ID,因为我只想打印名称。
public class DataLoader {
@Published var userData: [String:Int] = [:]
init() {
load()
}
func load() {
if let fileLocation = Bundle.main.url(forResource: "itemInfo", withExtension: "json") {
do {
let data = try Data(contentsOf: fileLocation)
let jsonDecoder = JSONDecoder()
let dataFromJson = try jsonDecoder.decode([ String: Int].self, from: data)
self.userData = dataFromJson
} catch {
print(error)
}
}
}
}
如何使用tableViewController中的所有项目名称填充tableview?
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel!.text = // not sure what goes here to populate list with names.
return cell
}
声明userData
为数组。更换
@Published var userData: [String:Int] = [:]
与
@Published var userData: [String] = []
并将字典键分配给数组
self.userData = Array(dataFromJson.keys)
在cellForRow
显示中以给定索引的项目
cell.textLabel!.text = userData[indexPath.row]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句