在Swift中以编程方式进行Segue [英] Make Segue programmatically in Swift
问题描述
我有两个VC:VC1和VC2。
在VC1中,我有一个完成按钮
我以编程方式制作了一个结果数组
我想通过到VC2。
I have two VCs: VC1 and VC2.
In VC1, I have a finish button
which I programmatically made and a result array
I want to pass to VC2.
我知道如何在故事板中制作Segue,但是由于完成按钮$ c $,我现在不能这样做c>以编程方式制作。
I know how to make Segue in Storyboard, but I cannot do that at this moment since the finish button
is programmatically made.
如果我想使用segue传递结果数组,有没有办法以编程方式生成segue?如果这不可能,我应该使用 presentViewController
来呈现VC2并设置委托来传递结果数组
?
If I want to pass result array using segue, is there a way to make the segue programmatically? If this is not possible, should I just present VC2 using presentViewController
and set a delegate to pass the result array
?
推荐答案
你可以像在这个答案中提出的那样做:
InstantiateViewControllerWithIdentifier 。
You can do it like proposed in this answer: InstantiateViewControllerWithIdentifier.
此外我正在为您提供代码来自Swift中重写的链接答案,因为链接中的答案最初是用Objective-C编写的。
Furthermore I am providing you the code from the linked answer rewritten in Swift because the answer in the link was originally written in Objective-C.
let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewControllerWithIdentifier("identifier") as! SecondViewController
vc.resultsArray = self.resultsArray
self.navigationController?.pushViewController(vc, animated:true)
编辑:
由于这个答案引起了一些关注,我想我还会为您提供更多故障安全方式。在上面的回答中,如果带有identifier的 ViewController
不是类型 SecondViewController $ c,应用程序将崩溃$ C>。在Swift中,您可以通过使用可选绑定来防止此崩溃:
Since this answer draws some attention I thought I provide you with another more failsafe way. In the above answer the application will crash if the ViewController
with "identifier" is not of type SecondViewController
. In Swift you can prevent this crash by using optional binding:
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
上。
This way the ViewController
is pushed if it is of type SecondViewController
. If can not be casted to SecondViewController
a message is printed and the application remains on the current ViewController
.
这篇关于在Swift中以编程方式进行Segue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!