20

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
1
  • What is your question? What have you tried, what problems did it have, and what did you find when trying to debug those problems?
    – NobodyNada
    Commented Jun 27, 2016 at 0:42

2 Answers 2

44

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

1
  • Is there any way to get the action of button by tags or index?
    – Alok
    Commented Aug 18, 2017 at 7:27
20

here´s a sample code with two actions plus and ok-action:

import UIKit

// The UIAlertControllerStyle ActionSheet is used when there are more than one button.
@IBAction func moreActionsButtonPressed(sender: UIButton) {
    let otherAlert = UIAlertController(title: "Multiple Actions", message: "The alert has more than one action which means more than one button.", preferredStyle: UIAlertControllerStyle.ActionSheet)

    let printSomething = UIAlertAction(title: "Print", style: UIAlertActionStyle.Default) { _ in
        print("We can run a block of code." )
    }

    let callFunction = UIAlertAction(title: "Call Function", style: UIAlertActionStyle.Destructive, handler: myHandler)

    let dismiss = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)

    // relate actions to controllers
    otherAlert.addAction(printSomething)
    otherAlert.addAction(callFunction)
    otherAlert.addAction(dismiss)

    presentViewController(otherAlert, animated: true, completion: nil)
}

func myHandler(alert: UIAlertAction){
    print("You tapped: \(alert.title)")
}}

with i.E. handler: myHandler you define a function, to read the result of the let printSomething.

This is just one way ;-)

Any questions?

2
  • thanks! Does presentViewController show the alert?
    – Abhi V
    Commented Jun 26, 2016 at 21:26
  • @Abhi V yes, that´s right!
    – Ulli H
    Commented Jun 26, 2016 at 21:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.