Search code examples
iosswiftseguepresentviewcontroller

Make instance of view controller and segue to it programatically


I have two view controllers in my storyboard: view1 and view2.

In view1, I used the storyboard to make a segue from its tableview to view2.

But now in view2, I have programmatically created a button, and it is supposed to segue to another instantiated view2.

When the button is clicked, I made a function to execute:

func buttonPressed(sender: UIButton){
  //TODO:- GET NEXT PAGE
  self.performSegueWithIdentifier("anotherView2", sender: sender)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if(segue.identifier == "anotherView2"){
    let anotherView2Controller = segue.destinationViewController as! View2
    ...
    ...
  }
}

Of course it does not work, since there is no segue identifier called anotherView2. So I want to make it somehow, but I really cannot find good way to manage this.

Is there anyway to create the segue programmatically? I tried to make the segue from storyboard, but since the button is created programatically, I cannot segue to view2 to view2.


Solution

  • You want to use presentViewController instead of performSegue:

    // however you want to initialize the new vc
    let vc2 : View2 = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("view2.id") as! View2
    

    an alternate way to init the vc is to do this:

    let vc2 = View2()
    

    and then set the data and present:

    vc2.index = index // whatever you want to pass
    self.presentViewController(vc2, animated: true, completion: nil)
    

    Otherwise you could create a new view controller in your storyboard, but I wouldn't recommend it.