Vista de alerta rápida con Aceptar y Cancelar: ¿qué botón pulsó?


105

Tengo una vista de alerta en Xcode escrita en Swift y me gustaría determinar qué botón seleccionó el usuario (es un cuadro de diálogo de confirmación) para no hacer nada o ejecutar algo.

Actualmente tengo:

@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()
}

Probablemente estoy usando los botones incorrectamente, corríjame ya que todo esto es nuevo para mí.


Respuestas:


303

Si está usando iOS8, debería usar UIAlertController - UIAlertView está en desuso .

A continuación, se muestra un ejemplo de cómo utilizarlo:

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)

Como puede ver, los controladores de bloques para UIAlertAction manejan las pulsaciones de botones. Hay un gran tutorial aquí (aunque este tutorial no está escrito con swift): http://hayageek.com/uialertcontroller-example-ios/

Actualización de 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)

Actualización de 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
Puede utilizar el en UIAlertActionStyle.Cancellugar de .Defaulten su ejemplo.
— Tristan Warner-Smith

Si no quiero hacer nada en la acción Cancelar, ¿no puedo devolver nada?
— Gabriel Rodrigues

Por supuesto, técnicamente, no hago nada en el ejemplo más que registrar. Pero si elimino el registro, no estaría haciendo nada.
— Michael Wildermuth

1
es genial cuando las respuestas se actualizan para las versiones más recientes de Swift
— BlackTigerX

cualquiera sabe cómo agregar ID de accesibilidad a las acciones "ok" y "cancelar"
— 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

Actualizado para swift 3:

// definición de función:

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

// definición de función logoutFun ():

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

3

Puede hacer esto fácilmente 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)

.

Referencia: iOS Show Alert


0

Es posible que desee considerar el uso de SCLAlertView , alternativa para UIAlertView o UIAlertController .

UIAlertController solo funciona en iOS 8.xo superior, SCLAlertView es una buena opción para admitir versiones anteriores.

github para ver los detalles

ejemplo:

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")
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.