Getting the user’s attention with alerts and action sheets
Present important information to a person or prompt them about an important choice.
Overview
Display an alert or action sheet when your app requires additional information or acknowledgment from a person. Alerts and action sheets interrupt your app’s normal flow to display a message to the person. The following image shows an alert, which the person dismisses by selecting one of the listed options.
[Image]
The following image shows an action sheet. A person dismisses an action sheet by selecting one of the listed options, or by tapping outside an action sheet.
[Image]
Present an alert
To display an alert, create a UIAlertController object, configure it, and then call present(_:animated:completion:) with the object as a parameter, as shown in the following code. Configuring the alert controller includes specifying the title and message that you want the person to see and the actions they can select. Add at least one action — represented by a UIAlertAction object — to an alert controller before you present it.
@IBAction func agreeToTerms() {
// Create the action buttons for the alert.
let defaultAction = UIAlertAction(title: "Agree",
style: .default) { (action) in
// Respond to the person's selection of the action.
}
let cancelAction = UIAlertAction(title: "Disagree",
style: .cancel) { (action) in
// Respond to the person's selection of the action.
}
// Create and configure the alert controller.
let alert = UIAlertController(title: "Terms and Conditions",
message: "Click Agree to accept the terms and conditions.",
preferredStyle: .alert)
alert.addAction(defaultAction)
alert.addAction(cancelAction)
self.present(alert, animated: true) {
// The system presented the alert.
}
}Present an action sheet
Display an action sheet inside a popover on both iPhone and iPad. To display your action sheet in a popover, specify your popover’s anchor point using the popoverPresentationController property of your alert controller.
@IBAction func deleteItem() {
let destroyAction = UIAlertAction(title: "Delete",
style: .destructive) { (action) in
// Respond to user selection of the action.
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .cancel) { (action) in
// Respond to user selection of the action.
}
let alert = UIAlertController(title: "Delete the image?",
message: "",
preferredStyle: .actionSheet)
alert.addAction(destroyAction)
alert.addAction(cancelAction)
alert.popoverPresentationController?.sourceItem =
self.trashButton
self.present(alert, animated: true) {
// The system presented the alert.
}
}Configure the popover presentation controller’s sourceItem to anchor the popover to a UIBarButtonItem or NSToolbarItem. When a person taps the button, the popover animates from and replaces the specified item until they select an action item or dismiss the popover.
Alternatively, specify the anchor location for the popover using the sourceView and sourceRect properties.