1

我的应用程序中有一个对象数组,它传递给另一个名为 restaurantViewController 的 VC,该值存储在 restMenu 中,现在的问题是,每当我滚动 UITableView 时,ItemQuantityCell 值总是被重用为 0,这是我的 restMenu 中的默认值如何更新我的 restMenu 中的值,以便我可以将它传递给 checkoutVC,并为我的 ItemQuantityCell 提供正确的值。我的数据来自哪里的 plist 如下

餐厅文件.plist

这是我的代码

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

}
4

1 回答 1

1

根据您的 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值。将对象传递restMenu给 otherViewController并更新其ItemQuant。如果您向后导航,只需重新加载您的 tableview 数据。它将显示ItemQuant的变化。

于 2018-05-18T06:34:09.697 回答