Abhi V Abhi V - 5 months ago 23
Swift Question

How to add actions to UIAlertController and get result of actions (Swift)

I want to set up four action buttons on my

UIAlertController
with a title for each and I want to return the title of the button that is pressed. In short, here is my plan:

Create a new alert controller
for i in ["hearts", "spades", "diamonds", "hearts"] {
add action button to alert
set title of button to i
}
return currentTitle() of action button that was clicked

Answer

Try this:

let alert = UIAlertController(title: "Alert Title", message: "Alert Message, style = .Alert)
for i in ["hearts", "spades", "diamonds", "hearts"] {
    alert.addAction(UIAlertAction(title: i, style: .Default, handler: doSomething)
}
self.presentViewController(alert, animated: true, completion: nil)

And handle the action here:

func doSomething(action: UIAlertAction) {
    //Use action.title
}

For future reference, you should take a look at Apple's Documentation on UIAlertControllers