Gurvier Singh Dhillon
Gurvier Singh Dhillon

Reputation: 137

Swift 2 - How do I switch to another ViewController when the AlertController appears?

I am trying to switch to another ViewController once I click 'OK' on the AlertController. Currently when I click 'OK' it stays on the current ViewController. How can this be done? thanks.

This code is presented in ViewController1 and I want to change to ViewController4 once I have clicked 'OK' when the AlertController appears.

Code Below:

  @IBAction func submitTapped(sender: AnyObject) {
    print("Validating...")
    validator.validate(self)
    Button1.hidden = false
}

// MARK: ValidationDelegate Methods

func validationSuccessful() {
    print("Validation Success!")
    let alert = UIAlertController(title: "Success", message: "You are validated!", preferredStyle: UIAlertControllerStyle.Alert)
    let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: {action in ViewController4))
        alert.addAction(defaultAction) - Error Code // Variable used within its own initial value
        self.presentViewController(alert, animated: true, completion: nil)

        } - Error Code //Expected ‘,’ separator

Upvotes: 0

Views: 642

Answers (1)

Cristik
Cristik

Reputation: 32783

You need to add a handler to the OK action:

let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: {action in
    performSegueWithIdentifier("controller4SequeIdentifier", sender: nil);
})
alert.addAction(defaultAction)
self.presentViewController(alert, animated: true, completion: nil)

In the handler you can switch to the other controller. Note that this will happen after the user presses the OK button. You also need to add a seque to ViewController4 in your storyboard, and give it an identifier to match the one passed to performSegueWithIdentifier.

Upvotes: 2

Related Questions