mijares93 mijares93 - 6 months ago 18
Swift Question

How to Show a UIAlertController and Perform an Action when User clicks OK?

I am stuck with a

UIAlertController
.

I have this alert view:

@IBAction func AddPatientButton(sender: AnyObject) {
let alert = UIAlertController(title:"Registro Paciente", message: "Paciente Registrado", preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title:"Ok", style: UIAlertActionStyle.Default, handler: nil))

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


}


And it shows me an alert view correctly. But what I want is that when the user press the button Ok, this button performs a segue and send the user to another ViewController.

Answer

This sample code does what you want.

@IBAction func AddPatientButton(sender: AnyObject) {

    let alert = UIAlertController(title:"Registro Paciente", message: "Paciente Registrado", preferredStyle: UIAlertControllerStyle.Alert)

    alert.addAction(UIAlertAction(title:"Ok", style: UIAlertActionStyle.Default, handler: { alertAction in

   // Code to segue/change VC !
   self.performSegueWithIdentifier("segue_name", animated: true)
   //

}))

Just make sure to create a segue to the view controller you want to go to AND to give that segue an identifier in the inspector (click on the segue and check the inspector). Then copy paste that identifier where "segue_name" is.

Let me show it in images:

1) Add a new VC (unless you already have one you want to go to obviously). Then Ctrl-drag from the yellow icon of the VC you come from to the VC you want to go to:

Here it is

2) Select Show or any option you are looking for:

Here it is

3) Select the segue (the arrow that appeared), click on the Attributes Inspector (Top Right), and fill in the identifier:

enter image description here

Then copy paste that identifier where "segue_name" is in the code I gave you.