Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 606
Abhi V Avatar asked Jun 26 '16 18:06

Abhi V


2 Answers

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

like image 55
Pranav Wadhwa Avatar answered Nov 15 '22 22:11

Pranav Wadhwa


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?

like image 25
Ulli H Avatar answered Nov 15 '22 22:11

Ulli H