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

时间:2018-01-15 17:51:47

标签: arrays swift uitableview

这是我的字典:

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
}

2 个答案:

答案 0 :(得分:0)

Instead of creating a dictionary to hold your data, define a struct for each result then create an array of those structs.

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

Then:

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
]

Now that you have your data organized properly, your table view methods become:

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
}

This approach has many advantages. You can easily and safely add additional details if needed. You can sort the table view as needed by sorting the array on whichever field you want.

答案 1 :(得分:0)

One solution would be:

  1. create struct instead of dictionary

    struct dataModel {
    
      var foodName: String
    
      var calories: Int
    }
    
  2. Keep struct object into array

  3. Can access them using index of array and show the value in table cell.