How to Call a Function when Ok is pressed in an UIAlert

Hunter picture Hunter · Sep 12, 2015 · Viewed 14.9k times · Source

Im try to simply call a function called "GoToNewShoot" When the user press the "ok" button when the Alert pops up Thanks!.

Code:

   @IBAction func GobacktoCamera(sender: AnyObject) {
    var alertController = UIAlertController(title: "Just Checking", message: "Are You Sure You Want to Start over ", preferredStyle: UIAlertControllerStyle.Alert)
    alertController.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Cancel, handler: nil))
    self.presentViewController(alertController, animated: true, completion: nil)

Answer

Dharmesh Kheni picture Dharmesh Kheni · Sep 12, 2015

You can do it by using handler from addAction this way:

@IBAction func GobacktoCamera(sender: AnyObject) {

    var alertController = UIAlertController(title: "Just Checking", message: "Are You Sure You Want to Start over", preferredStyle: UIAlertControllerStyle.Alert)

    alertController.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { action in
        //run your function here
        self.GoToNewShoot()
    }))

    self.presentViewController(alertController, animated: true, completion: nil)
}


func GoToNewShoot(){

    println("Method Called")
}