UIAlert Action Function Creation
Complete guide to creating reusable UIAlert functions for user notifications and confirmations in iOS apps
Note:
This tutorial covers creating reusable UIAlert functions for displaying pop-up alerts to users. This is essential for providing user feedback, error messages, and confirmation dialogs in iOS apps.
Overview
You may want to share pop-up warnings for information, errors, or options after actions from users. For this, we use the UIAlert Action parameter.
To use this code block more easily in different areas, you can perform operations by calling a function.
Reference:
- Swift — CocoaPods — Firebase Integration
- Firebase User Registration
- Firebase User Login
- Firebase User Redirect
- Profile Photo Selection
- Firebase Storage Upload
Step 1: Basic UIAlert Function
In the example usage, we will write a UIAlert Action function consisting of a title, message, and OK button.
You can perform the operations that will occur when the OK button is pressed with the completion section, and you can add more buttons with UIAlertAction changes with alert.addAction.
func showAlert(title: String, message: String, completion: (() -> Void)? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
completion?()
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
Step 2: Complete Implementation
Here's a complete implementation with various alert types:
import UIKit
class AlertViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI() {
// Add buttons to test different alert types
let simpleAlertButton = UIButton(type: .system)
simpleAlertButton.setTitle("Simple Alert", for: .normal)
simpleAlertButton.addTarget(self, action: #selector(showSimpleAlert), for: .touchUpInside)
let confirmationAlertButton = UIButton(type: .system)
confirmationAlertButton.setTitle("Confirmation Alert", for: .normal)
confirmationAlertButton.addTarget(self, action: #selector(showConfirmationAlert), for: .touchUpInside)
let actionSheetButton = UIButton(type: .system)
actionSheetButton.setTitle("Action Sheet", for: .normal)
actionSheetButton.addTarget(self, action: #selector(showActionSheet), for: .touchUpInside)
let customAlertButton = UIButton(type: .system)
customAlertButton.setTitle("Custom Alert", for: .normal)
customAlertButton.addTarget(self, action: #selector(showCustomAlert), for: .touchUpInside)
}
// MARK: - Alert Functions
@objc func showSimpleAlert() {
showAlert(title: "Information", message: "This is a simple alert message.")
}
@objc func showConfirmationAlert() {
showConfirmationAlert(
title: "Confirm Action",
message: "Are you sure you want to proceed?",
confirmTitle: "Yes",
cancelTitle: "No"
) {
// Handle confirmation
print("User confirmed the action")
self.showAlert(title: "Success", message: "Action confirmed!")
}
}
@objc func showActionSheet() {
showActionSheet(
title: "Choose Option",
message: "Select an option from the list",
actions: [
("Option 1", .default) { print("Option 1 selected") },
("Option 2", .default) { print("Option 2 selected") },
("Cancel", .cancel) { print("Cancelled") }
]
)
}
@objc func showCustomAlert() {
showCustomAlert(
title: "Custom Alert",
message: "This alert has custom styling and multiple actions",
actions: [
("Save", .default) { self.saveData() },
("Delete", .destructive) { self.deleteData() },
("Cancel", .cancel) { print("Cancelled") }
]
)
}
// MARK: - Alert Helper Functions
func showAlert(title: String, message: String, completion: (() -> Void)? = nil) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
completion?()
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
func showConfirmationAlert(
title: String,
message: String,
confirmTitle: String = "OK",
cancelTitle: String = "Cancel",
onConfirm: @escaping () -> Void
) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: confirmTitle, style: .default) { _ in
onConfirm()
}
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: nil)
alert.addAction(confirmAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
func showActionSheet(
title: String?,
message: String?,
actions: [(String, UIAlertAction.Style, () -> Void)]
) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .actionSheet)
for (title, style, action) in actions {
let alertAction = UIAlertAction(title: title, style: style) { _ in
action()
}
alert.addAction(alertAction)
}
present(alert, animated: true, completion: nil)
}
func showCustomAlert(
title: String,
message: String,
actions: [(String, UIAlertAction.Style, () -> Void)]
) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
for (title, style, action) in actions {
let alertAction = UIAlertAction(title: title, style: style) { _ in
action()
}
alert.addAction(alertAction)
}
present(alert, animated: true, completion: nil)
}
// MARK: - Example Actions
private func saveData() {
// Simulate saving data
print("Data saved successfully")
showAlert(title: "Success", message: "Data has been saved successfully!")
}
private func deleteData() {
showConfirmationAlert(
title: "Delete Confirmation",
message: "Are you sure you want to delete this item? This action cannot be undone.",
confirmTitle: "Delete",
cancelTitle: "Cancel"
) {
print("Data deleted")
self.showAlert(title: "Deleted", message: "Item has been deleted successfully!")
}
}
}
Step 3: Advanced Alert Features
Alert with Text Input
func showAlertWithTextField(
title: String,
message: String,
placeholder: String = "",
confirmTitle: String = "OK",
cancelTitle: String = "Cancel",
onConfirm: @escaping (String) -> Void
) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addTextField { textField in
textField.placeholder = placeholder
textField.autocapitalizationType = .sentences
}
let confirmAction = UIAlertAction(title: confirmTitle, style: .default) { _ in
if let textField = alert.textFields?.first {
onConfirm(textField.text ?? "")
}
}
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: nil)
alert.addAction(confirmAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
// Usage example
@objc func showNameInputAlert() {
showAlertWithTextField(
title: "Enter Name",
message: "Please enter your name:",
placeholder: "Your name"
) { name in
print("User entered name: \(name)")
self.showAlert(title: "Welcome", message: "Hello, \(name)!")
}
}
Alert with Multiple Text Fields
func showAlertWithMultipleTextFields(
title: String,
message: String,
fields: [(String, String, UIKeyboardType)], // (placeholder, defaultValue, keyboardType)
onConfirm: @escaping ([String]) -> Void
) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
for (placeholder, defaultValue, keyboardType) in fields {
alert.addTextField { textField in
textField.placeholder = placeholder
textField.text = defaultValue
textField.keyboardType = keyboardType
}
}
let confirmAction = UIAlertAction(title: "OK", style: .default) { _ in
let values = alert.textFields?.map { $0.text ?? "" } ?? []
onConfirm(values)
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(confirmAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
// Usage example
@objc func showUserInfoAlert() {
showAlertWithMultipleTextFields(
title: "User Information",
message: "Please enter your details:",
fields: [
("Name", "", .default),
("Email", "", .emailAddress),
("Phone", "", .phonePad)
]
) { values in
let name = values[0]
let email = values[1]
let phone = values[2]
print("User info: \(name), \(email), \(phone)")
}
}
Alert with Custom Styling
func showStyledAlert(
title: String,
message: String,
style: UIAlertController.Style = .alert,
tintColor: UIColor? = nil
) {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
// Handle OK action
}
alert.addAction(okAction)
// Custom styling
if let tintColor = tintColor {
alert.view.tintColor = tintColor
}
present(alert, animated: true, completion: nil)
}
Step 4: Error Handling Alerts
Network Error Alert
func showNetworkErrorAlert(retryAction: @escaping () -> Void) {
let alert = UIAlertController(
title: "Network Error",
message: "Please check your internet connection and try again.",
preferredStyle: .alert
)
let retryAction = UIAlertAction(title: "Retry", style: .default) { _ in
retryAction()
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(retryAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
Validation Error Alert
func showValidationErrorAlert(field: String, message: String) {
let alert = UIAlertController(
title: "Validation Error",
message: "\(field): \(message)",
preferredStyle: .alert
)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
Step 5: Alert Manager Class
Centralized Alert Management
class AlertManager {
static let shared = AlertManager()
private init() {}
weak var presentingViewController: UIViewController?
func setPresentingViewController(_ viewController: UIViewController) {
presentingViewController = viewController
}
func showSuccessAlert(title: String, message: String) {
showAlert(title: title, message: message, style: .alert)
}
func showErrorAlert(title: String, message: String) {
showAlert(title: title, message: message, style: .alert)
}
func showConfirmationAlert(
title: String,
message: String,
onConfirm: @escaping () -> Void
) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Yes", style: .default) { _ in
onConfirm()
}
let cancelAction = UIAlertAction(title: "No", style: .cancel, handler: nil)
alert.addAction(confirmAction)
alert.addAction(cancelAction)
presentingViewController?.present(alert, animated: true, completion: nil)
}
private func showAlert(title: String, message: String, style: UIAlertController.Style) {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
presentingViewController?.present(alert, animated: true, completion: nil)
}
}
// Usage in ViewController
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
AlertManager.shared.setPresentingViewController(self)
}
func someAction() {
AlertManager.shared.showSuccessAlert(
title: "Success",
message: "Operation completed successfully!"
)
}
}
Note:
UIAlert functions are essential for user communication in iOS apps. Remember to create reusable, accessible, and user-friendly alert functions that enhance the user experience without being intrusive.