Mastering UIAlertController in Swift

Alerts and Action Sheets Made Simple: A Swift Guide to UIAlertController Mastery

Vikram Kumar
5 min readDec 4, 2023

Swift’s UIAlertController is a powerful and flexible class that allows developers to display alerts and action sheets in iOS applications. Whether you need to inform users about critical information, prompt them for input, or present a set of actions, UIAlertController is an essential tool in your iOS development toolkit. In this article, we'll explore the various components of both alert and action sheet views and learn how to leverage their capabilities effectively, including working with dynamic content, using a helper class, and extending UIViewController for enhanced usability.

Understanding UIAlertController

UIAlertController is part of the UIKit framework in iOS and is used for presenting alerts and action sheets. It replaces the older UIAlertView and UIActionSheet classes, providing a more versatile and customizable solution.

Creating a Simple Alert

Let’s start with a basic example of creating a simple alert with a title and a message. This is the fundamental structure of an alert:

let alertController = UIAlertController(title: "Hello", message: "Welcome to UIAlertController", preferredStyle: .alert)

let okAction = UIAlertAction(title: "OK", style: .default) { _ in
// Handle OK button tap
}

alertController.addAction(okAction)

present(alertController, animated: true, completion: nil)

In this example, we create an alert with a title “Hello” and a message “Welcome to UIAlertController.” The alert includes a single action, an “OK” button. When the “OK” button is tapped, the closure inside okAction is executed.

Adding Multiple Actions

UIAlertController allows you to add multiple actions, providing users with different choices. Here’s an example of an alert with “Yes” and “No” buttons:

let alertController = UIAlertController(title: "Confirmation", message: "Do you want to proceed?", preferredStyle: .alert)

let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
// Handle Yes button tap
}

let noAction = UIAlertAction(title: "No", style: .cancel) { _ in
// Handle No button tap
}

alertController.addAction(yesAction)
alertController.addAction(noAction)

present(alertController, animated: true, completion: nil)

In this case, we’ve added two actions: “Yes” and “No.” The “Yes” button has a default style, while the “No” button has a cancel style, indicating it’s a less preferred option.

Using Action Sheet

UIAlertController can also be used to present action sheets, which are useful for displaying a set of related actions. Here’s an example:

let actionSheetController = UIAlertController(title: "Options", message: "Choose an action", preferredStyle: .actionSheet)

let action1 = UIAlertAction(title: "Action 1", style: .default) { _ in
// Handle Action 1
}

let action2 = UIAlertAction(title: "Action 2", style: .destructive) { _ in
// Handle Action 2
}

let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
// Handle Cancel button tap
}

actionSheetController.addAction(action1)
actionSheetController.addAction(action2)
actionSheetController.addAction(cancelAction)

present(actionSheetController, animated: true, completion: nil)

In this example, we’ve created an action sheet with two actions, “Action 1” and “Action 2,” and a cancel action. Action sheets are typically used on larger devices like iPads or when you have a set of actions related to the current context.

Adding Text Input Fields

UIAlertController allows the inclusion of text input fields, enabling users to provide information. Here’s an example of an alert with a text input field:

let alertController = UIAlertController(title: "Enter Your Name", message: nil, preferredStyle: .alert)

alertController.addTextField { textField in
textField.placeholder = "Name"
}

let submitAction = UIAlertAction(title: "Submit", style: .default) { _ in
if let text = alertController.textFields?.first?.text {
// Handle submitted text
}
}

alertController.addAction(submitAction)

present(alertController, animated: true, completion: nil)

In this case, we’ve added a text input field to the alert, and the user can input their name. The entered text can be accessed through the text property of the text field.

UIAlertController with Helper Class

Creating a helper class of UIAlertController allows for flexibility in displaying content. Here’s an example using a helper function:

class AlertHelper {
static func showAlertWithActions(title: String, message: String, actions: [UIAlertAction]) -> UIAlertController {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)

for action in actions {
alertController.addAction(action)
}

return alertController
}
}

// Example usage
let actions = [
UIAlertAction(title: "Option 1", style: .default) { _ in /* Handle Option 1 */ },
UIAlertAction(title: "Option 2", style: .default) { _ in /* Handle Option 2 */ },
]

let dynamicAlert = AlertHelper.showAlertWithActions(title: "Alert", message: "Choose an option", actions: actions)

present(dynamicAlert, animated: true, completion: nil)

This helper function allows you to create alerts with varying actions based on the specific context.

UIViewController Extension for UIAlertController

Extending UIViewController with a custom function for presenting alerts further enhances code organization and readability:

extension UIViewController {

func presentSimpleAlert(title: String = "App Name", message: String) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)

alertController.addAction(UIAlertAction(title: "OK", style: .default))

present(alertController, animated: true, completion: nil)
}

func presentAlert(title: String, message: String, preferredStyle: UIAlertController.Style = .alert, actions: [UIAlertAction]) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)

for action in actions {
alertController.addAction(action)
}
present(alertController, animated: true, completion: nil)
}
}

// Example usage: 1
self.presentSimpleAlert(message: "Please enter username and password.")

// Example usage: 2
let actions = [
UIAlertAction(title: "Confirm", style: .default) { _ in
/* Handle confirm action */
},
UIAlertAction(title: "Cancel", style: .cancel) { _ in /* Handle Cancel */ },
]

presentAlert(title: "Action Required", message: "Choose an action", actions: actions)

This extension simplifies the process of presenting alerts within any view controller.

Conclusion

UIAlertController is a powerful tool for handling alerts and action sheets in Swift. Through the examples provided, you’ve learned how to create simple alerts, add multiple actions, use action sheets, incorporate text input fields, and create dynamic alerts. By leveraging helper functions and extensions, you can enhance the maintainability of your code and provide a seamless user experience in your iOS applications. Experiment with these examples and incorporate UIAlertController into your Swift development toolkit for effective user interaction.

Thank you for reading until the end. Before you go:

--

--

Vikram Kumar
Vikram Kumar

Written by Vikram Kumar

I am Vikram, a Senior iOS Developer at Matellio Inc. focused on writing clean and efficient code. Complex problem-solver with an analytical and driven mindset.

Responses (1)