ios - 通过函数 prepare for segue 将数据传递给 ViewController 不起作用

标签 ios swift null

我正在尝试使用以下函数将数据传递给 ViewController:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? ContactTableViewController
    {
        vc.invitationType = type
        print(vc.invitationType)
    }
}

调用正常,我可以打印 vc.invitationType,以便在新的 vc 中设置该变量。

问题是转场发生的时间。在新的 View Controller 中,行 print(inv) 没有被执行,因为 invitationType 是 nil:

class ContactTableViewController: UITableViewController {

    var invitationType: InvitationType?

    override func viewDidLoad() {
        super.viewDidLoad()
        if let inv = invitationType {
            print(inv)
        }
    }
}

谁能解释为什么会这样?

编辑: 我以为我正在使用 Storyboard 中定义的 segue,但事实证明,我错误地使用了我的一个实例化另一个 ViewController 的函数:

    let newVC = originVC.storyboard?.instantiateViewController(withIdentifier: viewcontroller) as! VC
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.window?.rootViewController = newVC

所以问题是我最终在一个实例中设置了变量 invitationType 并转到了 ContactTableViewController 的另一个实例。

最佳答案

试试这个,可能 view 在那个时候已经加载了,所以在你将值设置为 invitationType 之前调用了 viewDidLoad:

class ContactTableViewController: UITableViewController {

    var invitationType: InvitationType? {
        didSet {
            print(">>> already loaded \(invitationType)")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if let inv = invitationType {
            print(inv)
        }
    }
}

根据评论,这两个 ContactTableViewController 并不相同 - 您通过实例化另一个显示的 View Controller 以某种方式搞乱了 segue。

关于ios - 通过函数 prepare for segue 将数据传递给 ViewController 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48642826/

相关文章:

ios - 如何在函数中将运算符作为参数传递?

null - null 和 space 有点区别

c# - 什么是NullReferenceException,如何解决?

ios - iOS 9.0 中的 UITextview 字体为零

ios - 无法使用 '[NSObject : AnyObject]' 类型的索引为 'String' 类型的值添加下标

iOS 区域监控,设备重启后位置不会发生重大变化

iOS 应用程序在后台播放音乐时被终止

ios - 动态调整 UITableViewCell 大小

swift - 如何为多个屏幕保存 NSWindow 位置?

MySQL 3 列唯一约束不起作用,可能是由于 NULL