我有两个VC:VC1和VC2。 在VC1中,我有一个经过程序编写的“完成”按钮和一个要传递给VC2的“结果数组”。
我知道如何在Storyboard中创建Segue,但此时无法这样做,因为“完成”按钮是通过程序编写的。
如果我想使用segue传递result数组,是否有办法通过编程方式创建segue? 如果不可能,那我应该使用“presentViewController”显示VC2并设置代理来传递“结果数组”吗?
您可以按照此答案的建议进行操作:InstantiateViewControllerWithIdentifier。
此外,我提供了链接答案中用Swift重写的代码,因为该链接中的答案最初是用Objective-C编写的。
let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "identifier") as! SecondViewController
vc.resultsArray = self.resultsArray
编辑:
由于这个回答引起了一些关注,我认为我应该再提供一种更加安全的方法。在上面的回答中,如果 "identifier" 对应的 ViewController
不是 SecondViewController
类型,应用程序将会崩溃。在 Swift 中,你可以使用可选绑定来防止这种崩溃:
guard let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewControllerWithIdentifier("identifier") as? SecondViewController else {
print("Could not instantiate view controller with identifier of type SecondViewController")
return
}
vc.resultsArray = self.resultsArray
self.navigationController?.pushViewController(vc, animated:true)
如果ViewController
是SecondViewController
类型,就会被推入。如果不能强制转换为SecondViewController
,则会打印一条消息,并保留在当前ViewController
上。
UIViewController
到UIViewController
segue,并使用performSegueWithIdentifier调用它似乎是更好的解决方案。 - Duncan Cfinish
函数中调用performSegueWithIdentifier:
,传递您的segue名称,就这样。在prepareForSegue
方法中,您可以通过访问segue.identifier
找出正在执行哪个segue,如果是相关的segue,则可以获取指向segue.destinationViewController
的指针,并以这种方式传递数据。
performSegueWithIdentifier
。然后,在prepareForSegue
中,您将放入一个if
语句来识别您正在使用的segue,获取从VC1传递的任何内容,在VC2上进行指定并完成...您就完成了。 - Adrian