Controlador de escritura para UIAlertAction


104

Le estoy presentando un UIAlertViewal usuario y no puedo entender cómo escribir el controlador. Este es mi intento:

let alert = UIAlertController(title: "Title",
                            message: "Message",
                     preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                            handler: {self in println("Foo")})

Tengo un montón de problemas en Xcode.

La documentación dice convenience init(title title: String!, style style: UIAlertActionStyle, handler handler: ((UIAlertAction!) -> Void)!)

Los bloques / cierres completos están un poco por encima de mi cabeza en este momento. Cualquier sugerencia es muy apreciada.

Respuestas:


165

En lugar de self en su controlador, ponga (alert: UIAlertAction!). Esto debería hacer que su código se vea así

    alert.addAction(UIAlertAction(title: "Okay",
                          style: UIAlertActionStyle.Default,
                        handler: {(alert: UIAlertAction!) in println("Foo")}))

esta es la forma correcta de definir controladores en Swift.

Como señaló Brian a continuación, también hay formas más fáciles de definir estos controladores. El uso de sus métodos se analiza en el libro, consulte la sección titulada Cierres


9
{alert in println("Foo")}, {_ in println("Foo")}y {println("Foo")}también debería funcionar.
Brian Nickel

7
@BrianNickel: El tercero no funciona porque necesita manejar la acción del argumento. Pero además de eso, no tiene que escribir UIAlertActionStyle.Default en rápido. El valor predeterminado también funciona.
Ben

Tenga en cuenta que si usa "let foo = UIAlertAction (...), entonces puede usar la sintaxis de cierre final para poner lo que podría ser un cierre largo después de UIAlertAction - se ve bastante bien de esa manera.
David H

1
Aquí hay una manera elegante de escribir esto:alert.addAction(UIAlertAction(title: "Okay", style: .default) { _ in println("Foo") })
Harris

74

Las funciones son objetos de primera clase en Swift. Entonces, si no desea usar un cierre, también puede simplemente definir una función con la firma adecuada y luego pasarla como handlerargumento. Observar:

func someHandler(alert: UIAlertAction!) {
    // Do something...
}

alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                              handler: someHandler))

¿Cómo debería verse esta función de controlador en el objetivo-C?
andilabs

1
Las funciones son cierres en Swift :) que pensé que era bastante bueno. Consulte los documentos: developer.apple.com/library/ios/documentation/Swift/Conceptual/…
kakubei

17

Puede hacerlo tan simple como esto usando swift 2:

let alertController = UIAlertController(title: "iOScreator", message:
        "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
        self.pressed()
}))

func pressed()
{
    print("you pressed")
}

    **or**


let alertController = UIAlertController(title: "iOScreator", message:
        "Hello, world!", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Destructive,handler: { action in
      print("pressed")
 }))

Todas las respuestas anteriores son correctas, solo estoy mostrando otra forma en que se puede hacer.


11

Supongamos que desea una acción UIAlertAction con título principal, dos acciones (guardar y descartar) y el botón cancelar:

let actionSheetController = UIAlertController (title: "My Action Title", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)

    //Add Cancel-Action
    actionSheetController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))

    //Add Save-Action
    actionSheetController.addAction(UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
        print("handle Save action...")
    }))

    //Add Discard-Action
    actionSheetController.addAction(UIAlertAction(title: "Discard", style: UIAlertActionStyle.Default, handler: { (actionSheetController) -> Void in
        print("handle Discard action ...")
    }))

    //present actionSheetController
    presentViewController(actionSheetController, animated: true, completion: nil)

Esto funciona para swift 2 (Xcode versión 7.0 beta 3)


7

Cambio de sintaxis en swift 3.0

alert.addAction(UIAlertAction(title: "Okay",
                style: .default,
                handler: { _ in print("Foo") } ))

7

En Swift 4:

let alert=UIAlertController(title:"someAlert", message: "someMessage", preferredStyle:UIAlertControllerStyle.alert )

alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.default, handler: {
        _ in print("FOO ")
}))

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

4

así es como lo hago con xcode 7.3.1

// create function
func sayhi(){
  print("hello")
}

// crea el botón

let sayinghi = UIAlertAction(title: "More", style: UIAlertActionStyle.Default, handler:  { action in
            self.sayhi()})

// agregando el botón al control de alerta

myAlert.addAction(sayhi);

// el código completo, este código agregará 2 botones

  @IBAction func sayhi(sender: AnyObject) {
        let myAlert = UIAlertController(title: "Alert", message:"sup", preferredStyle: UIAlertControllerStyle.Alert);
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:nil)

        let sayhi = UIAlertAction(title: "say hi", style: UIAlertActionStyle.Default, handler:  { action in
            self.sayhi()})

        // this action can add to more button
        myAlert.addAction(okAction);
        myAlert.addAction(sayhi);

        self.presentViewController(myAlert, animated: true, completion: nil)
    }

    func sayhi(){
        // move to tabbarcontroller
     print("hello")
    }

4

crear alerta, probado en xcode 9

let alert = UIAlertController(title: "title", message: "message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: self.finishAlert))
self.present(alert, animated: true, completion: nil)

y la función

func finishAlert(alert: UIAlertAction!)
{
}

2
  1. En Swift

    let alertController = UIAlertController(title:"Title", message: "Message", preferredStyle:.alert)
    
    let Action = UIAlertAction.init(title: "Ok", style: .default) { (UIAlertAction) in
        // Write Your code Here
    }
    
    alertController.addAction(Action)
    self.present(alertController, animated: true, completion: nil)
  2. En el objetivo C

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *OK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
    {
    }];
    
    [alertController addAction:OK];
    
    [self presentViewController:alertController animated:YES completion:nil];
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.