Make Segue programmatically in Swift

后端 未结 2 1481
太阳男子
太阳男子 2020-12-18 20:25

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.

I know

2条回答
  •  萌比男神i
    2020-12-18 20:49

    You can do it like proposed in this answer: InstantiateViewControllerWithIdentifier.

    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).instantiateViewController(withIdentifier: "identifier") as! SecondViewController
    
    vc.resultsArray = self.resultsArray
    

    EDIT:

    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)
    

    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.

提交回复
热议问题