如何用字典键值填充表视图?
How to populate tableview with dictionary key-values?
我有一个名为 itemInfo.json 的本地 JSON 文件,其中包含一个字典,其中包含将近 6000 个键值对,其中包含一个项目名称和一个项目 ID。
{ "itemName1" : 2564,
"itemName2" : 470,
"itemName3" : 1849,
"itemName4" : 60,
"itemName5" : 103 }
// continues for a few thousand more
我在将 JSON 文件加载到控制台时没有遇到问题,但我不知道如何将项目名称打印到列表中的表视图中。列表中不需要 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]
我有一个名为 itemInfo.json 的本地 JSON 文件,其中包含一个字典,其中包含将近 6000 个键值对,其中包含一个项目名称和一个项目 ID。
{ "itemName1" : 2564,
"itemName2" : 470,
"itemName3" : 1849,
"itemName4" : 60,
"itemName5" : 103 }
// continues for a few thousand more
我在将 JSON 文件加载到控制台时没有遇到问题,但我不知道如何将项目名称打印到列表中的表视图中。列表中不需要 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]