ios - 我怎样才能更新我的字典 ios Swift 中的数量值

标签 ios swift uitableview nsdictionary arrayofarrays

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

ResturantFile.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

}

最佳答案

根据您的 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/

相关文章:

ios - 更改 NSAttributedString 文本颜色而无需再次设置标题

ios - tableview 不想快速重新加载

ios - 下载时如何处理iOS应用程序 sleep 后崩溃?

ios - 自定义单元格设置 ImageView

ios - 原型(prototype)单元格未显示在 UITableView 中

ios - reloadData 不适用于 UITableView 数据源?

ios - ios native 应用程序中标签的超链接功能

ios - iOS 10.2 上 textView 的无限循环

swift - 来自按钮的时间戳?

ios - 如何使用一个 var 或 let 从一个 View Controller 到另一个 View Controller