Keywords: iOS | UIAlertController | Swift | Alert | Actions | Closures
Abstract: This article provides a detailed guide on implementing custom actions for alert buttons in iOS applications with Swift. It covers the transition from UIAlertView to UIAlertController, step-by-step code examples, and best practices for handling button clicks with closures.
Introduction
In modern iOS development, the UIAlertController class is the standard way to present alerts and action sheets. Unlike the deprecated UIAlertView, UIAlertController allows for more flexible button configurations and uses closures to handle user interactions. This article demonstrates how to add a custom button to an alert that calls a specific function, such as a retry function.
Creating the UIAlertController
To start, create an instance of UIAlertController with a title, message, and preferred style. For alerts, use .alert.
let alertController = UIAlertController(title: "Ooops", message: "Unable to log in.", preferredStyle: .alert)Adding UIAlertAction for Custom Buttons
Next, create UIAlertAction instances for each button. For example, to add an "OK" button that dismisses the alert and a "Retry" button that calls a function.
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
// Optionally handle OK action
}
let retryAction = UIAlertAction(title: "Retry", style: .default) { _ in
self.retry() // Call the custom function
}Adding Actions to the Controller
Add the actions to the alert controller using the addAction method.
alertController.addAction(okAction)
alertController.addAction(retryAction)Presenting the Alert
Finally, present the alert controller from the current view controller.
self.present(alertController, animated: true, completion: nil)Complete Code Example
Here is a complete example based on the original question:
func showLoginErrorAlert() {
let alertController = UIAlertController(title: "Ooops", message: "Unable to log in.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
// Optionally handle OK action
}
let retryAction = UIAlertAction(title: "Retry", style: .default) { _ in
self.retry()
}
alertController.addAction(okAction)
alertController.addAction(retryAction)
self.present(alertController, animated: true, completion: nil)
}
func retry() {
// Implement retry logic here
print("Retry function called")
}Why Use UIAlertController Over UIAlertView
UIAlertController is part of the UIKit framework and integrates better with modern iOS APIs. It supports closures for action handling, making the code more concise and readable. Additionally, UIAlertView has been deprecated since iOS 9, so using UIAlertController is essential for future compatibility.
Conclusion
By using UIAlertController, developers can easily add custom actions to alert buttons in Swift iOS. This approach leverages closures for clean and efficient event handling. Remember to always use the latest APIs to ensure app compatibility and maintainability.