gpt4 book ai didi

arrays - 将字典键和值重用到可重用单元格中

转载 作者:行者123 更新时间:2023-11-30 11:51:46 25 4
gpt4 key购买 nike

这是我的字典:

Results = ["Orange Salad + Pasta with Salmon + Cheesecake": 464, 
"Orange Salad + Pesto Pasta + Crab Cake": 480,
"Rice Salad + Pesto Pasta + Cheesecake white ": 538,
"Salad Endives + Salmon Pasta + Crab Cake ": 480,
"Salad Endives + Pesto Pasta + Crab Cake ": 450,
"Orange Salad + Salmon Pasta + Cake crab": 510]

如何更新 dequeueReusableCell 方法以重用键和值并为每个单元格填充两个标签。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CombinationCell", for: indexPath) as! CombinationTableViewCell

cell.combinaisonLabel.text = ""
cell.calories.text = ""

return cell
}

最佳答案

不要创建字典来保存数据,而是为每个结果定义一个结构,然后创建这些结构的数组。

struct NutritionInfo {
let name: String
let calories: Int
}

然后:

let results = [
NutritionInfo(name: "Orange Salad + Pasta with Salmon + Cheesecake", calories: 464),
NutritionInfo(name: "Orange Salad + Pesto Pasta + Crab Cake", calories: 480),
// and the rest
]

现在您已经正确组织了数据,您的表格 View 方法将变为:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return results.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CombinationCell", for: indexPath) as! CombinationTableViewCell

let nutrition = results[indexPath.row]

cell.combinaisonLabel.text = nutrition.name
cell.calories.text = "\(nutrition.calories)"

return cell
}

这种方法有很多优点。如果需要,您可以轻松安全地添加其他详细信息。您可以根据需要对 TableView 进行排序,方法是根据您想要的字段对数组进行排序。

关于arrays - 将字典键和值重用到可重用单元格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48268258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com