2016-06-26 36 views
6

Desidero impostare uno UIAlertController con quattro pulsanti di azione e i titoli dei pulsanti da impostare su "cuori", "picche", "quadri" e "club". Quando viene premuto un pulsante, voglio restituire il titolo.Come aggiungere azioni a UIAlertController e ottenere il risultato di azioni (Swift)

In breve, ecco il mio piano:

// 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

Qual è la tua domanda? Che cosa hai provato, quali problemi ha avuto e cosa hai trovato durante il tentativo di eseguire il debug di questi problemi? – NobodyNada

risposta

21

Prova questo:

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) 

E gestire l'azione qui:

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

Per riferimento futuro, si dovrebbe dare un'occhiata a Apple's Documentation on UIAlertControllers

+0

C'è un modo per ottenere l'azione del pulsante per tag o indice? – Alok

10

here's un campione con due azioni più un 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)") 
} 

}

con vale a dire Gestore : myHandler si definisce una funzione, per leggere il risultato di il lasciare printSomething.

Questo è solo uno modo ;-)

Tutte le domande?

+0

grazie! PresentViewController mostra l'avviso? –

+0

@Abhi V sì, è vero! –