Displaying Alerts
Alerts in UIKit are implemented using UIAlertController
with the .alert
style to present critical information, prompt user input, or confirm actions. This document covers displaying alerts, adding text fields, and managing alert severity, including the severity
property introduced in iOS 18 for Mac Catalyst.
Displaying Alerts to the User
Alerts are modal dialogs that interrupt the user flow to communicate important information or request a decision. They are created using UIAlertController
with the preferredStyle
set to .alert
.
Key Components
- UIAlertController: Manages the alert’s presentation and content.
- UIAlertAction: Defines buttons (actions) with titles, styles, and handlers.
- Presentation: Displayed modally, centered on iPhone and iPad (no popover required for
.alert
style).
Basic Example
import UIKit
class ViewController: UIViewController {
@IBAction func showAlert(_ sender: UIButton) {
let alert = UIAlertController(title: "Warning", message: "Your session is about to expire.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
print("OK tapped")
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
print("Cancel tapped")
}
alert.addAction(okAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
}
Key Points
- Title and Message: Use
title
for a brief headline andmessage
for details. Both are optional but recommended for clarity. - Actions: Add at least one
UIAlertAction
to dismiss the alert. The.cancel
style is typically used for dismissal. - Presentation: Use
present(_:animated:completion:)
to show the alert modally. - iPad: Alerts are centered and do not require popover configuration.
Adding Text Fields to an Alert
Text fields can be added to alerts to collect user input, such as a name or password.
Implementation
Use addTextField(configurationHandler:)
to add and configure text fields.
Example
@IBAction func showTextFieldAlert(_ sender: UIButton) {
let alert = UIAlertController(title: "Enter Name", message: "Please provide your name.", preferredStyle: .alert)
alert.addTextField { textField in
textField.placeholder = "Your name"
textField.keyboardType = .default
textField.autocapitalizationType = .words
}
let submitAction = UIAlertAction(title: "Submit", style: .default) { _ in
if let text = alert.textFields?.first?.text {
print("Entered: \(text)")
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alert.addAction(submitAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
Key Points
- Accessing Input: Retrieve input via
alert.textFields
in the action handler. - Multiple Text Fields: Add multiple text fields by calling
addTextField
multiple times. - Configuration: Customize with properties like
placeholder
,isSecureTextEntry
, orkeyboardType
. - Validation: Validate input in the handler or disable actions using
isEnabled
.
Dynamic Action Enabling
Disable the submit action until valid input is provided:
alert.addTextField { textField in
textField.placeholder = "Your name"
NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: .main) { _ in
submitAction.isEnabled = !(textField.text?.isEmpty ?? true)
}
}
submitAction.isEnabled = false // Initially disabled
Changing the Severity of an Alert
In iOS 18, UIAlertController
includes a severity
property for Mac Catalyst apps, allowing developers to specify the alert’s severity using the UIAlertControllerSeverity
enum (.default
or .critical
). For standard iOS apps on iPhone/iPad, severity is conveyed through action styles, language, and visual customizations, as no severity
property exists.
Severity Property (Mac Catalyst, iOS 18+)
For Mac Catalyst apps, set the severity
property to indicate the alert’s importance:
@IBAction func showCriticalAlert(_ sender: UIButton) {
let alert = UIAlertController(title: "Critical Error", message: "Data could not be saved.", preferredStyle: .alert)
#if targetEnvironment(macCatalyst)
alert.severity = .critical // Set severity for Mac Catalyst
#endif
let retryAction = UIAlertAction(title: "Retry", style: .default) { _ in
print("Retry tapped")
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alert.addAction(retryAction)
alert.addAction(cancelAction)
// Emphasize severity with tint (all platforms)
alert.view.tintColor = .systemRed
present(alert, animated: true, completion: nil)
}
Conveying Severity on iOS (iPhone/iPad)
For standard iOS apps, use these techniques:
- Action Styles: Use
.destructive
for high-severity actions (e.g., delete),.default
for neutral actions, and.cancel
for dismissal. - Title and Message: Use urgent language for critical alerts (e.g., “Error” or “Warning”).
- Tint Color: Adjust
view.tintColor
to emphasize severity (e.g., red for errors).
Example (iOS)
@IBAction func showHighSeverityAlert(_ sender: UIButton) {
let alert = UIAlertController(title: "Error", message: "Failed to save data. Retry?", preferredStyle: .alert)
let retryAction = UIAlertAction(title: "Retry", style: .default) { _ in
print("Retry tapped")
}
let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { _ in
print("Delete tapped")
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alert.addAction(retryAction)
alert.addAction(deleteAction)
alert.addAction(cancelAction)
alert.view.tintColor = .systemRed // Visual cue for severity
present(alert, animated: true, completion: nil)
}
Key Points
- Mac Catalyst Severity: Use
alert.severity = .critical
or.default
for Mac Catalyst apps to indicate importance. - iOS Severity: Rely on
.destructive
actions, urgent language, andtintColor
for iPhone/iPad apps. - Conditional Compilation: Use
#if targetEnvironment(macCatalyst)
to safely accessseverity
only for Mac Catalyst. - Consistency: Follow iOS conventions (e.g., red for destructive actions) for user familiarity.
Best Practices
- Clarity: Use concise titles and messages to communicate intent.
- Minimal Actions: Limit to 2–3 actions to avoid overwhelming users.
- Cancel Action: Include a
.cancel
action for dismissal, typically placed last. - Accessibility: Ensure text fields and actions are VoiceOver-compatible with descriptive labels.
- Testing: Test on iPhone, iPad, and Mac Catalyst (if applicable) to verify behavior.
- Severity: Use the
severity
property for Mac Catalyst or design cues for iOS to match the alert’s purpose. - Text Fields: Validate input and provide clear placeholders.
Limitations
- Severity Availability: The
severity
property is exclusive to Mac Catalyst in iOS 18 and not available for standard iOS apps. - Customization: Alerts have limited visual customization to maintain system consistency.
- Modal Nature: Alerts interrupt the user flow, so use sparingly for critical messages.
- Single Cancel: Only one
.cancel
action is supported.
Summary
Alerts in UIKit, created with UIAlertController
in .alert
style, are used to display critical information or collect input via text fields. The severity
property, available in iOS 18 for Mac Catalyst, allows setting .critical
or .default
severity, but standard iOS apps rely on action styles, language, and tint colors to convey severity. By following best practices, developers can create effective and accessible alerts for both iOS and Mac Catalyst environments.