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

49,180

Solution 1

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

Solution 2

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?

Share:
49,180

Related videos on Youtube

Abhi V
Author by

Abhi V

Updated on July 09, 2022

Comments

  • Abhi V
    Abhi V almost 2 years

    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
    
  • Abhi V
    Abhi V almost 8 years
    thanks! Does presentViewController show the alert?
  • Ulli H
    Ulli H almost 8 years
    @Abhi V yes, that´s right!
  • Alok
    Alok almost 7 years
    Is there any way to get the action of button by tags or index?