小编典典

在Swift中以编程方式制作Segue

swift

我有两个VC:VC1和VC2。在VC1中,我有一个finish button以编程方式制作的,并且result array我想传递给VC2。

我知道如何在情节提要中制作Segue,但由于这finish button是通过编程方式制作的,因此目前我不能这样做。

如果我想使用segue传递结果数组,是否有办法以编程方式进行segue?如果这不可能,我是否应该只使用VC2
presentViewController并设置一个委托来传递result array


阅读 279

收藏
2020-07-07

共1个答案

小编典典

您可以像在此答案中建议的那样进行操作:
InstantiateViewControllerWithIdentifier

此外,由于链接中的答案最初是用Objective-C编写的,因此我为您提供了用Swift重写的链接答案中的代码。

let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "identifier") as! SecondViewController

vc.resultsArray = self.resultsArray

编辑:

由于此答案引起了一定的关注,我想我为您提供了另一种更安全的方法。在上述答案中,如果ViewControllerwith “ identifier”
不是type,则应用程序将崩溃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

2020-07-07