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

Abhi V picture Abhi V · Jun 26, 2016 · Viewed 46.6k times · Source

I want to set up a UIAlertController with four action buttons, and the titles of the buttons to be set to "hearts", "spades", "diamonds", and "clubs". When a button is pressed, I want to return its title.

In short, here is my plan:

// TODO: Create a new alert controller

for i in ["hearts", "spades", "diamonds", "clubs"] {

    // TODO: Add action button to alert controller

    // TODO: Set title of button to i

}

// TODO: return currentTitle() of action button that was clicked

Answer

Pranav Wadhwa picture Pranav Wadhwa · Jun 26, 2016

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