在Swift中,使用字典存储TableView所需的数据是非常常见的。下面是一个示例代码,展示如何遍历字典并在TableView中显示。
假设我们有一个存储以下信息的字典:
var items = [ ["name": "item1", "price": 100], ["name": "item2", "price": 200], ["name": "item3", "price": 300] ]
在TableView中显示数据需要进行以下步骤:
var array = Array(items.values)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return array.count }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let item = array[indexPath.row]
cell.textLabel?.text = item["name"]
cell.detailTextLabel?.text = "$\(item["price"]!)" // force unwrapping here, the dictionary always includes `price`
return cell
}
override func viewDidLoad() { super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
这就是将遍历字典并在TableView中显示的简单实现方式。
上一篇:遍历字典元素并将它们添加到列表中
下一篇:遍历字典值以形成URL