domingo, 15 de junio de 2014

Creación de Alertas y ActionSheet con Swift.

Creación de Alertas y ActionSheet con Swift.

En esta ocasión, vamos a ver como crear alertas sencillas y actionSheet, usando el nuevo lenguaje de programación presentado por Apple en la ultima WWDC.
Swift difiere un poco respecto a Objective C.



Para crear una alerta sencilla usamos el siguiente código:

var alertaDos = UIAlertController(title: "Titulo", message: "Cuerpo del mensaje", preferredStyle: UIAlertControllerStyle.Alert)

//Ahora es mucho mas sencillo, y podemos añadir nuevos botones y usar handler para capturar el botón seleccionado y hacer algo.

        alertaDos.addAction(UIAlertAction(title: "Salir" , style: UIAlertActionStyle.Cancel ,handler: {alerAction in
            println("Pulsado el boton de Salir")
            }))

//Para hacer que la alerta se muestre usamos presentViewController, a diferencia de Objective C que como recordaremos se usa [Show Alerta]

        self.presentViewController(alertaDos, animated: true, completion: nil)




Esto nos muestra este tipo de alerta y al pulsar en el botón "Salir" Nos muestra por consola: Pulsado el botón de Salir. 





Alerta ActionSheet:

Este tipo de alerta que aparece de forma modal desde abajo hacia arriba, el código necesario en Swift es el siguiente:

var action : UIAlertController = UIAlertController(title: "Alerta", message: "Seleciona un  Valor", preferredStyle: UIAlertControllerStyle.ActionSheet)


//Al igual que en la alerta normal con addAction añadimos nuevos botones y con handler capturamos el botón pulsado por el usuario y hacemos algo.
        action.addAction(UIAlertAction(title: "Valor 1", style: UIAlertActionStyle.Default, handler: { alertAction in
            println("Click en Valor 1")
            action.dismissModalViewControllerAnimated(true);
            }))

 //Con UIAlertActionStyle podemos elegir el tipo de botón que vamos a usar en este caso usamos Destructive que nos mostraría el texto del botón en rojo.
        action.addAction(UIAlertAction(title: "Valor 2", style: UIAlertActionStyle.Destructive, handler: { alertAction in
            println("Click en Valor 2")
            action.dismissModalViewControllerAnimated(true);
            }))
        


        action.addAction(UIAlertAction(title: "Cancelar", style: UIAlertActionStyle.Cancel, handler: {alertAction in
            println("Click en Cancelar")
            action.dismissModalViewControllerAnimated(true);
            }))
        

        self.presentViewController(action, animated: true, completion: nil)




Espero les guste, proximamente seguiré añadiendo mas cosas sobre Swift.

Saludos y espero sus sugerencias.


@promedi46