Swift: Navigate to new ViewController using button

First off as I explain in this answer, you need to drag the segue from the overall UIViewController to the next UIViewController, i.e. you shouldn’t specifically connect the UIButton (or any IBOutlet for that matter) to the next UIViewController if the transition’s conditional:

storyboard segue

You’ll also need to assign an identifier to the segue. To do so, you can select the segue arrow then type in an identifier within the right-hand panel:

segue identifier

Then to perform the actual segue, use the performSegueWithIdentifier function within your conditional, like so:

if user != nil {
    self.messageLabel.text = "You have logged in";
    self.performSegueWithIdentifier("segueIdentifier", sender: self)
} else {
    self.messageLabel.text = "You are not registered";
}

where “segueIdentifier” is the identifier you’ve assigned to your segue within the storyboard.

Leave a Comment