Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

How to Display an Alert View with Swift

Display an Alert View with Swift

First we'll create a constant of UIAlertController. Since we'll be using an alert, the UIAlertControllerStyle is set to default. It can have other values such as ActionSheet, Alert, and RawValue.

 let alertPrompt = UIAlertController(title: "Simple Alert View", message: "Hello, World", preferredStyle: UIAlertControllerStyle.Alert)

Next, we'll be adding a button inside the newly created alertcontroller. We'll set the handler to nil since we don't need any action yet. But you may call a function when a button is click by setting the handler to some function. 
Note: The handler function must have a parameter of UIAlertAction type (e.g. func buttonHandler(alertView: UIAlertAction){})

alertPrompt.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:nil))
            
And lastly in order to show the alert view, you must present it by the calling the presentViewController method.


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

Summary of Code:

Inside an action function, place the following line of codes.

let alertPrompt = UIAlertController(title: "Simple Alert View", message: "Hello, World", preferredStyle: UIAlertControllerStyle.Alert)

alertPrompt.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:nil))
            

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

or to handle a button click in the alert view, we can have

let alertPrompt = UIAlertController(title: "Simple Alert View", message: "Hello, World", preferredStyle: UIAlertControllerStyle.Alert)

alertPrompt.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:"btn_clicked"))
            

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

Then we can declare the button handle:

func btn_clicked(alertView: UIAlertAction!){
        presentViewController(imagePicker, animated: true, completion: nil)
 println("Ok")
 }

How to Display an Alert View with Swift How to Display an Alert View with Swift Reviewed by Edmond Legaspi on Wednesday, January 28, 2015 Rating: 5

No comments:

Powered by Blogger.