我的应用程序中有一个对象数组,该对象传递给另一个名为 restaurantViewController 的 VC,该值存储在 restMenu 中,现在问题是每当我滚动 UITableView 时,ItemQuantityCell 值总是被重用为 0,这是默认值在我的 restMenu 中,我如何更新我的 restMenu 中的值,以便我可以将它传递给 checkoutVC,并为我的 ItemQuantityCell 提供正确的值。 我的数据来源列表如下
这是我的代码
var restMenu = [[String:Any]]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! RestaurantItemViewCell
cell.delegate = self as? TableViewCellDelegate
cell.selectionStyle = UITableViewCellSelectionStyle.none
//assign item name to cell
let selectedDictName = restMenu[indexPath.row] as NSDictionary
print("the selected dict ", selectedDictName)
cell.itemNameLabel.text = selectedDictName.value(forKey: "ItemName") as? String
// assign item price to cell
let selectedDictPrice = restMenu[indexPath.row] as NSDictionary
cell.itemPriceLabel.text = "Price: \(selectedDictPrice.value(forKey: "ItemPrice") as! String)"
// assign item quantity to cell
let selectedDictQuant = restMenu[indexPath.row] as NSDictionary
cell.itemQuantityLabel.text = selectedDictQuant.value(forKey: "ItemQuant") as? String
}
最佳答案
根据您的 plist,ItemQuant 始终为零,并且您在 cell.itemQuantityLabel.text
中分配相同的值,因此它始终为零。
接下来,请更改您的代码,不要在 Swift 中使用 NSStuff。
像下面这样更新你的cellForRowAt indexPath
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! RestaurantItemViewCell
cell.delegate = self as? TableViewCellDelegate
cell.selectionStyle = UITableViewCellSelectionStyle.none
//assign item name to cell
let dict = restMenu[indexPath.row]
print("the selected dict ", dict)
cell.itemNameLabel.text = dict["ItemName"] as! String
cell.itemPriceLabel.text = dict["ItemPrice"] as! String
cell.itemQuantityLabel.text = dict["ItemQuant"] as! String
return cell
}
希望这对你有用。
仅供引用。以上代码未经测试。仅供引用。
注意 无论您想在哪里更新项目数量 获取要更新数量的索引,如下操作
restMenu[index]["ItemQuant"] = "2" // index is you will get somehow & 2 is just for example you can do what you want there.
更新
根据您最后的评论,这是建议。
代替字典结构,创建适当的模型类,并解析 plist,您的 cellForRowAt indexPath
将被更改,您的 ItemQuant 必须是 Int 值(value)。将 restMenu
对象传递给其他 ViewController
并更新其 ItemQuant。如果您向后导航,只需重新加载您的表格 View 数据。它将向您显示 ItemQuant 的变化。
关于ios - 我怎样才能更新我的字典 ios Swift 中的数量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50404915/