Programmatically changing View Controllers without

2019-05-04 02:20发布

问题:

I want to switch to a new view controller when I press a button without using a navigation controller and I can't seem to be able to do this. I have looked everywhere for an answer but everything that I have found is either in objective-c, using a navigation controller, or not working at all.

func gunsoutButtonPressed(sender:UIButton!) {
    print("yay\t")
    //let encounterVC:AnyObject! = self.storyboard?.instantiateViewControllerWithIdentifier("ecounterViewController")
    //self.showViewController(encounterVC as UIViewController, sender: encounterVC)
    let encounterViewController = self.storyboard.instantiateViewControllerWithIdentifier("encounterViewController") as encounterViewController
    self.pushViewController(encounterViewController, animated: true)
}

回答1:

You have to connect the two ViewControllers you would like to use. Then name the segue however you want and then use the following code to trigger the segue (inside an IBAction or something). It is not completely programmatically but you can trigger them programmatically, which should be enough.

performSegueWithIdentifier("mySegue", sender: nil)

Check out this video for support.

Hope this helps :)



回答2:

You cannot use a push segue without a UINavigationController. You could achieve this with a modal segue, such as this:

self.presentViewController(encounterViewController, animated: true, completion: nil)


回答3:

Segue

So you use the Segue ID to make sure you segue correctly.

No Segue

I would suggest doing this instead though:

let vc = ViewControllerToSegueTo()
self.presentViewController(vc, animated: true, completion: nil)

It is slightly better if you do not want to use the storyboard.