2016-06-26 20 views
6

Chcę ustawić UIAlertController za pomocą czterech przycisków akcji, a tytuły przycisków, które mają być ustawione na "serca", "piki", "diamenty" i "kluby". Po naciśnięciu przycisku chcę zwrócić jego tytuł.Jak dodać akcje do UIAlertController i uzyskać wyniki działań (Swift)

W skrócie, oto mój 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

Jakie jest Twoje pytanie? Co próbowaliście, jakie mieliście problemy i co znaleźliście, próbując rozwiązać te problemy? – NobodyNada

Odpowiedz

21

Spróbuj tego:

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) 

i obsługiwać działania tutaj:

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

Na przyszłość, należy przyjrzeć Apple's Documentation on UIAlertControllers

+0

Czy istnieje sposób na uzyskanie działania przycisku według znaczników lub indeksu? – Alok

10

here's próbka z dwóch działań plus OK działania:

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

}

z tj handler: myHandler Użytkownik definiuje funkcję, aby odczytać wynik z let printSomething.

To tylko jeden way ;-)

Wszelkie pytania?

+0

dzięki! Czy presentViewController pokazuje alert? –

+0

@Abhi V tak, to prawda! –