Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the UIAlertController from UIAlertAction?

I want to call a function rather than use a closure with a UIAlertAction. Is it possible to get a reference to the UIAlertController that owns the UIAlertAction?

alert = UIAlertController(title: "City", message: "Enter a city name", preferredStyle: UIAlertControllerStyle.Alert)
UIAlertActionStyle.Default, handler: okAlert)

//...

func okAlert(action: UIAlertAction) {
    // Get to alert here from action?
}
like image 510
Mitchell Hudson Avatar asked Oct 05 '15 02:10

Mitchell Hudson


1 Answers

An action has no reference to its containing alert. Still, it's just a matter of planning ahead. If you need okAlert to have a reference to the alert controller, then give it that reference:

func okAlert(_ action: UIAlertAction, _ alert:UIAlertController) {
    // Get to alert here?
    // yes! it is `alert`!
}

You will still need a closure to capture alert and pass it:

let alert = UIAlertController(
    title: "City", message: "Enter a city name", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title:"OK", style:.Default, handler: {
    action in self.okAlert(action, alert)
}))

There may be details to work out. But the point is, if you want okAlert to live somewhere else, you can do it.

like image 64
matt Avatar answered Nov 15 '22 21:11

matt