2016-06-26 4 views
6

Ich möchte eine UIAlertController mit vier Aktionstasten einrichten und die Titel der Schaltflächen auf "hearts", "pikes", "diamonds" setzen und "Clubs". Wenn eine Taste gedrückt wird, möchte ich ihren Titel zurückgeben.So fügen Sie Aktionen zu UIAlertController hinzu und erhalten das Ergebnis von Aktionen (Swift)

Kurz gesagt, hier ist mein 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 
+0

Was ist Ihre Frage? Was hast du probiert, welche Probleme hattest du und was hast du beim Debuggen dieser Probleme gefunden? – NobodyNada

Antwort

21

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) 

Und die Aktion behandeln hier:

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

Für die Zukunft, sollten Sie einen Blick auf Apple's Documentation on UIAlertControllers nehmen

+0

Gibt es eine Möglichkeit, die Aktion der Schaltfläche durch Tags oder Index zu erhalten? – Alok

10

Heres eine Probe mit zwei Aktionen sowie eine ok-Aktion:

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)") 
} 

}

mit d Handler: myHandler Sie definieren eine Funktion, um das Ergebnis die zu lesen, lassen Sie printSomething.

Dies ist nur ein Weg ;-)

Noch Fragen?

+0

danke! Zeigt presentViewController die Warnung? –

+0

@Abhi V ja, das stimmt! –

Verwandte Themen