Swift
UIAlertView
iOS Development
SwiftUI
Programming Tutorial

How would I create a UIAlertView in Swift?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In the world of iOS development, presenting a user-friendly alert is crucial for improving the user experience. In older versions of iOS, UIAlertView was the go-to class for displaying alerts. However, with the introduction of iOS 8, Apple deprecated UIAlertView in favor of UIAlertController. This change not only modernized the approach to creating alerts but also provided a more flexible and powerful API for developers. In this article, we will explore how to create a similar functionality using UIAlertController in Swift.

Creating Alerts Using UIAlertController

Understanding UIAlertController

UIAlertController is a class in iOS that manages the display of alert messages to the user. It can be used to show alerts with actions, input fields, or even as simple informational pop-ups. The UIAlertController can have two styles:

  • Alert: Used to display a pop-up dialog to capture user input or prompt the user with options.
  • Action Sheet: Used to present a set of options from the bottom of the screen, typically on bigger screen devices like iPads.

Basic Setup

Before setting up your UIAlert, make sure you have a UIViewController from which you will present your alert. Now let's dive into creating a UIAlertController.

Example: Creating a Simple Alert

Here's a step-by-step example of how to create a basic alert with a single "OK" action in Swift:

swift
1import UIKit
2
3class ViewController: UIViewController {
4    
5    override func viewDidLoad() {
6        super.viewDidLoad()
7        
8        // Create the alert controller
9        let alertController = UIAlertController(title: "Alert Title",
10                                                message: "This is a simple alert",
11                                                preferredStyle: .alert)
12        
13        // Create the OK action
14        let okAction = UIAlertAction(title: "OK", style: .default) { _ in
15            // Handle the OK action here
16            print("OK tapped")
17        }
18        
19        // Add the action to the alert controller
20        alertController.addAction(okAction)
21        
22        // Present the alert
23        present(alertController, animated: true, completion: nil)
24    }
25}

Detailed Explanation

  1. Creating the Alert Controller:
    We initialize UIAlertController with a title, a message, and a preferred style (.alert in this case).
  2. Adding Actions:
    Actions are represented by UIAlertAction. An action can have a title, a specific style (like .default, .cancel, or .destructive), and a handler closure where the tap action is handled.
  3. Presenting the Alert:
    The present method is used to display the alert on the screen.

Adding Multiple Actions

You can add multiple actions to a single alert. Here's an example with an "OK" and a "Cancel" action:

swift
1import UIKit
2
3class ViewController: UIViewController {
4    
5    override func viewDidLoad() {
6        super.viewDidLoad()
7        
8        let alertController = UIAlertController(title: "Multiple Actions",
9                                                message: "Choose an option",
10                                                preferredStyle: .alert)
11        
12        let okAction = UIAlertAction(title: "OK", style: .default) { _ in
13            print("OK tapped")
14        }
15        
16        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
17            print("Cancel tapped")
18        }
19        
20        alertController.addAction(okAction)
21        alertController.addAction(cancelAction)
22        
23        present(alertController, animated: true, completion: nil)
24    }
25}

Handling Inputs with Text Fields

UIAlertController allows adding text fields for user input. Here's how to add this functionality:

swift
1import UIKit
2
3class ViewController: UIViewController {
4    
5    override func viewDidLoad() {
6        super.viewDidLoad()
7        
8        let alertController = UIAlertController(title: "Login",
9                                                message: "Enter your credentials",
10                                                preferredStyle: .alert)
11        
12        alertController.addTextField { textField in
13            textField.placeholder = "Username"
14        }
15        
16        alertController.addTextField { textField in
17            textField.placeholder = "Password"
18            textField.isSecureTextEntry = true
19        }
20        
21        let loginAction = UIAlertAction(title: "Login", style: .default) { _ in
22            let username = alertController.textFields?[0].text
23            let password = alertController.textFields?[1].text
24            print("Username: \(username ?? ""), Password: \(password ?? "")")
25        }
26        
27        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
28        
29        alertController.addAction(loginAction)
30        alertController.addAction(cancelAction)
31        
32        present(alertController, animated: true, completion: nil)
33    }
34}

In this example, we're adding two text fields: one for the username and another for the password. We use the addTextField method, supplying a configuration handler where properties like placeholder and isSecureTextEntry are set.

Summary

Here's a quick summary of tasks and key components used in creating alerts with UIAlertController:

TaskKey Component
Create AlertUIAlertController
Add ActionsUIAlertAction
Present Alertpresent() method
Handle Text InputsaddTextField(configurationHandler:)
Action Styles.default, .cancel, .destructive

Conclusion

The UIAlertController offers a versatile and modern approach to handling alerts in iOS applications using Swift. By supporting multiple actions and configurable text fields, it make it easier to engage with users by providing interactive and responsive alert dialogs. As you're developing iOS applications, adopting UIAlertController will ensure that your apps are up-to-date and providing a good user experience as mandated by contemporary iOS design patterns.


Course illustration
Course illustration

All Rights Reserved.