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?
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With