我有一本钥匙相同的字典:
var food = [["item" : "Burger", "image": "burger"],
["item" : "Pizza", "image": "pizza"],
["item" : "Lunch", "image": "lunch"],
["item" : "Coffee", "image": "coffee"]],
它在我的表视图中使用。每个单元格显示一个名称。
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
}
我想要的是,将选定单元格中的项值传递给第二个视图控制器。
我知道可以在整个函数中执行此操作,但无法从选定项中获取值。有人能帮我吗?
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??
}
最佳答案
像这样在RestaurantVC中创建一个属性
var selectedItem:String!
那就试试这个
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let indexPath = self.tableView.indexPathForSelectedRow?.row
let resVC = segue.destination as! RestaurantVC //second View controller
resVC.selectedItem = food[tableview.indexPathForSelectedRow.row]["item"] // How to do this??
}
关于ios - 如何通过tableView从字典中获取选定的值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43756954/