-
Notifications
You must be signed in to change notification settings - Fork 472
Using UIAlertController
You can choose whether to display as an alert or action sheet style.
The alert style presents modally in the center of their presenting view controllers.
Create the alert controller as below, setting preferredStyle to Alert
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
Create a UIAlertAction for each button to display and respond to.
// create a cancel action
let cancelAction = UIAlertAction(title: "OK", style: .cancel) { (action) in
// handle cancel response here. Doing nothing will dismiss the view.
}
// add the cancel action to the alertController
alertController.addAction(cancelAction)
// create an OK action
let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in
// handle response here.
}
// add the OK action to the alert controller
alertController.addAction(OKAction)
Adding two buttons will place them side by side in the alert. Adding more than two buttons stacks them in the view similar to the ActionSheet style.
present(alertController, animated: true) {
// optional code for what happens after the alert controller has finished presenting
}
If you wish to call present()
outside a view controller, you would do:
UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true) {
}
The action sheet style anchors the view to the bottom of the presenting view controller.
Create the alert controller as below, setting preferredStyle to ActionSheet
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .actionSheet)
Create a UIAlertAction for each button to display and respond to. The destructive style options shows the button text in red.
let logoutAction = UIAlertAction(title: "Log Out", style: .destructive) { (action) in
// handle case of user logging out
}
// add the logout action to the alert controller
alertController.addAction(logoutAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
// handle case of user canceling. Doing nothing will dismiss the view.
}
// add the cancel action to the alert controller
alertController.addAction(cancelAction)
present(alertController, animated: true) {
// optional code for what happens after the alert controller has finished presenting
}