1

Is it possible to connect a function to an UIAlertAction?

So after a user clicks the OK button it performs an action? Isn't this what the handler parameter does?

let alert: UIAlertController = UIAlertController(title: "Email already registered", message: "Please enter a different email", preferredStyle: .alert)
let okButton = UIAlertAction(title: "OK", style: .default, handler: backToLogin())

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

...

func backToLogin() {
    self.performSegueWithIdentifier("toLoginPage", sender: self)
}

2 Answers2

4

You can use a function as the handler, but it needs to have the correct type. Also you must not call it when you pass it as an argument, i.e., instead of handler: backToLogin() (which would set the return value of backToLogin as the handler) you would have handler: backToLogin without the ().

The following should work:

func backToLogin(alertAction: UIAlertAction) {
    self.performSegueWithIdentifier("toLoginPage", sender: self)
}
let okButton = UIAlertAction(title: "OK", style: .Default, handler: backToLogin)

But having to change backToLogin might defeat the purpose, so you could just use a closure:

let okButton = UIAlertAction(title: "OK", style: .Default) { _ in
    self.backToLogin()
}
Arkku
  • 41,011
  • 10
  • 62
  • 84
  • Worked perfect, thanks! I'm looking into closures more now...thanks again! –  Jul 24 '15 at 04:56
0
You need to enter the handler

let okButton = UIAlertAction(title: "OK", style: .Default, handler: {

(UIAlertAction) in

self.backToLogin()

})

}

See this answer for more info: Writing handler for UIAlertAction

Community
  • 1
  • 1
Fred Faust
  • 6,696
  • 4
  • 32
  • 55