Visualizzazione rapida degli avvisi con OK e Annulla: quale pulsante è stato toccato?


105

Ho una visualizzazione degli avvisi in Xcode scritta in Swift e vorrei determinare quale pulsante ha selezionato l'utente (è una finestra di dialogo di conferma) per non fare nulla o per eseguire qualcosa.

Attualmente ho:

@IBAction func pushedRefresh(sender: AnyObject) {
    var refreshAlert = UIAlertView()
    refreshAlert.title = "Refresh?"
    refreshAlert.message = "All data will be lost."
    refreshAlert.addButtonWithTitle("Cancel")
    refreshAlert.addButtonWithTitle("OK")
    refreshAlert.show()
}

Probabilmente sto usando i pulsanti in modo sbagliato, correggimi perché è tutto nuovo per me.


Risposte:


303

Se stai usando iOS8, dovresti usare UIAlertController - UIAlertView è deprecato .

Ecco un esempio di come usarlo:

var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
  print("Handle Ok logic here")
  }))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
  print("Handle Cancel Logic here")
  }))

presentViewController(refreshAlert, animated: true, completion: nil)

Come puoi vedere i gestori di blocchi per la maniglia UIAlertAction preme il pulsante. Un ottimo tutorial è qui (anche se questo tutorial non è stato scritto utilizzando swift): http://hayageek.com/uialertcontroller-example-ios/

Aggiornamento Swift 3:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
    print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
    print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

Aggiornamento Swift 5:

let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)

refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
      print("Handle Ok logic here")
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in
      print("Handle Cancel Logic here")
}))

present(refreshAlert, animated: true, completion: nil)

4
Potresti usare il UIAlertActionStyle.Cancelpiuttosto che .Defaultnel tuo esempio.
— Tristan Warner-Smith

Se non voglio fare nulla nell'azione Annulla non posso restituire nulla?
— Gabriel Rodrigues

Ovviamente, tecnicamente, nell'esempio non sto facendo altro che registrare. Ma se rimuovessi il registro non farei nulla.
— Michael Wildermuth

1
è fantastico quando le risposte vengono aggiornate per le nuove versioni di Swift
— BlackTigerX

chiunque sa come aggiungere l'ID di accessibilità alle azioni "ok" e "cancel"
— Kamaldeep singh Bhatia

18
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)

refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
    self.navigationController?.popToRootViewControllerAnimated(true)
}))

refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in

    refreshAlert .dismissViewControllerAnimated(true, completion: nil)


}))

presentViewController(refreshAlert, animated: true, completion: nil)

4

Aggiornato per swift 3:

// definizione della funzione:

@IBAction func showAlertDialog(_ sender: UIButton) {
        // Declare Alert
        let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to Logout?", preferredStyle: .alert)

        // Create OK button with action handler
        let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
             print("Ok button click...")
             self.logoutFun()
        })

        // Create Cancel button with action handlder
        let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
            print("Cancel button click...")
        }

        //Add OK and Cancel button to dialog message
        dialogMessage.addAction(ok)
        dialogMessage.addAction(cancel)

        // Present dialog message to user
        self.present(dialogMessage, animated: true, completion: nil)
    }

// definizione della funzione logoutFun ():

func logoutFun()
{
    print("Logout Successfully...!")
}

3

Puoi farlo facilmente usando UIAlertController

let alertController = UIAlertController(
       title: "Your title", message: "Your message", preferredStyle: .alert)
let defaultAction = UIAlertAction(
       title: "Close Alert", style: .default, handler: nil)
//you can add custom actions as well 
alertController.addAction(defaultAction)

present(alertController, animated: true, completion: nil)

.

Riferimento: iOS Show Alert


0

Potresti prendere in considerazione l'utilizzo di SCLAlertView , un'alternativa per UIAlertView o UIAlertController .

UIAlertController funziona solo su iOS 8.xo superiore, SCLAlertView è una buona opzione per supportare la versione precedente.

github per vedere i dettagli

esempio:

let alertView = SCLAlertView()
alertView.addButton("First Button", target:self, selector:Selector("firstButton"))
alertView.addButton("Second Button") {
    print("Second button tapped")
}
alertView.showSuccess("Button View", subTitle: "This alert view has buttons")
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.