在 uiviews 之间传输数据 nil

爱泼斯坦

嗨,我正在尝试将一个对象从一个 tableview 控制器传递给另一个。我正在使用准备转场和 didselectRowAt 函数:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.myDish = sections[indexPath.section].listofDishes?[indexPath.row]
    self.sectionName = sections[indexPath.section].sectionName!

    self.flag = 1
    performSegue(withIdentifier: "chooseDish", sender: self)
}



override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if self.flag != 0{
    let selectedDishTableViewController = segue.destination as! SelectedDishViewController
        selectedDishTableViewController.sectionName = self.sectionName
        selectedDishTableViewController.dish = self.myDish

        self.flag = 0
    }
}

我创建了这个标志,因为 preparefor segue 在 didselectrowat 之前被调用

我确保在准备转场之前设置 myDish 和 sectionName。

通过在我的第二个视图控制器中,我仍然将两个值都设为 nil。

这就是我在第二个控制器中声明变量的方式

var dish:Dish?
var sectionName:String?
小更

如果 prepareForSegue 在 didSelectRow 之前被调用,那么它意味着 segue 已经发生,所以第二次强制调用它时,通过在 didSelectRow 中显式调用 performSegue <- 它被忽略,因为视图控制器已经被使用这些变量的空值进行隔离。

这里的解决方案是做这样的事情:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let indexPath = tableView.indexPathForSelectedRow {
        let selectedDishTableViewController = segue.destination as! SelectedDishViewController
        selectedDishTableViewController.dish = sections[indexPath.section].listofDishes?[indexPath.row]
        selectedDishTableViewController.sectionName = sections[indexPath.section].sectionName!
    }
}

你不必在 tableView:didSelect... 中做任何其他事情,有了这个...让我知道它是否有效。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章