ios - 如何通过tableView从字典中获取选中的值?

标签 ios swift dictionary tableview

我有一本具有相同键的字典:

var food = [["item" : "Burger", "image": "burger"],
            ["item" : "Pizza", "image": "pizza"],
            ["item" : "Lunch", "image": "lunch"],
            ["item" : "Coffee", "image": "coffee"]],

并且在我的 TableView 中使用了它。每个单元格显示一个名称。

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

    let foodObjects = food[indexPath.row]

    cell.background.image = UIImage(named: foodObjects["image"]!)
    cell.nameLabel.text  = foodObjects["item"]

    return cell
}

我想要的是将所选单元格中的项目值传递给第二个 View Controller 。 我知道我可以在整个函数中执行此操作,但我无法从所选项目中获取值。有人可以帮助我吗?

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let indexPath = self.tableView.indexPathForSelectedRow?.row

    let resVC = segue.destination as! RestaurantVC //second View controller

    let selectedItem = food[indexPath.["item"]] // How to do this??
}

最佳答案

像这样创建属性

Controller 上的 selectedItem 变量。

On did select 将该项目保存到 selectediItem。

比在 prepare segue 方法中使用它。

关于ios - 如何通过tableView从字典中获取选中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43756954/

相关文章:

ios - 如何使用 Swift 以编程方式或从 Finder/Xcode 手动获取保存在文档中的 .plist?

macos - 在 OSX 中设置多行标签的高度

ios - 更改 .swift 以连接到 TableView Controller 而不是 View Controller

swift - 服务器端 Swift 的 LLDB 远程调试在 docker 和 macOS 中的 Linux 之间失败

python 初始化 dict 列表可能只是复制引用

javascript - 如何在数组中正确使用map()?

ios - 如何显示所有页面导航栏按钮

ios - 删除类构造函数 SWIFT 3 中存储的所有数据

java - 使用 JSON 返回 Java Map

ios - Swift 如何通过点击 map 注释上的右侧附件标注按钮来查看 View