Tutorial – UIAlert Pop Up Message
In this tutorial we will look at using the UIAlert controller to show pop up messages. First of all create a new xcode project, and add a button to your storyboard. Connect it up to ViewController.Swift with the action name as “showAlert”.
Now that we have done that to show an alert add in the following lines of code:
let alertController = UIAlertController(title: "My App", message: "Hey", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil)) self.present(alertController, animated: true, completion: nil)
The first line creates a new UIAlertController, where we set the title and message of the alert.
On the second line we add a button to the alert as there are none by default – this allows you to close the alert & also execute code associated with the button in the handler.
The third and final line presents the alert to the user.
Now run the code and you will see the alert below:
You can add more buttons with different styles as follows:
let alertController = UIAlertController(title: "My App", message: "Hey", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Default", style: UIAlertActionStyle.default, handler: nil)) alertController.addAction(UIAlertAction(title: "Destructive", style: UIAlertActionStyle.destructive, handler: nil)) alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)) self.present(alertController, animated: true, completion: nil)self.presentViewController(alertController, animated: true, completion: nil)
The corresponding styles are:
To make code run when you click on a button we simply add it to the handler as follows:
let alertController = UIAlertController(title: "My App", message: "Hey", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Print Yes", style: UIAlertActionStyle.default) { UIAlertAction in // Insert code to run on button click below self.printYes() }) self.present(alertController, animated: true, completion: nil)
And add the following function:
func printYes() { print("Yes") }
This code will print out yes to the console. Any code under the comment “// Insert code to run on button click below” will be run once that specified button on the alert has been pressed.