我正在尝试使用以下函数将数据传递给 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/