iOS

⌘K
  1. Home
  2. Docs
  3. iOS
  4. UI Controls
  5. Alerts and Action Sheets (UIAlertController)

Alerts and Action Sheets (UIAlertController)

What is UIAlertController?

UIAlertController is used to display alerts and action sheets in iOS apps. It provides important messages, confirmations, or options for the user to choose from.

There are two types of alerts:

  1. Alert – A pop-up in the center of the screen for important messages.
  2. Action Sheet – A menu from the bottom for choosing actions.

1. Creating a Basic Alert

A. Simple Alert with OK Button

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Show alert when the app starts
        showAlert()
    }
    
    func showAlert() {
        let alert = UIAlertController(title: "Hello!", 
                                      message: "This is a simple alert.", 
                                      preferredStyle: .alert)
        
        // Add OK button
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        
        // Present alert
        present(alert, animated: true, completion: nil)
    }
}

Explanation:

  • Creates an alert with a title and message.
  • Adds an OK button to dismiss the alert.
  • Shows the alert when the app loads.

2. Alert with Multiple Buttons

func showConfirmationAlert() {
    let alert = UIAlertController(title: "Confirm", 
                                  message: "Are you sure you want to delete this item?", 
                                  preferredStyle: .alert)

    let yesAction = UIAlertAction(title: "Yes", style: .destructive) { _ in
        print("Item deleted")
    }
    
    let noAction = UIAlertAction(title: "No", style: .cancel, handler: nil)
    
    alert.addAction(yesAction)
    alert.addAction(noAction)
    
    present(alert, animated: true, completion: nil)
}

Explanation:

  • Adds “Yes” (destructive red button) and “No” (cancel button).
  • Prints "Item deleted" if Yes is tapped.

3. Alert with Text Input

func showInputAlert() {
    let alert = UIAlertController(title: "Enter Name", 
                                  message: "Please enter your name below.", 
                                  preferredStyle: .alert)
    
    alert.addTextField { textField in
        textField.placeholder = "Your Name"
    }
    
    let submitAction = UIAlertAction(title: "Submit", style: .default) { _ in
        if let text = alert.textFields?.first?.text {
            print("Entered Name: \(text)")
        }
    }
    
    alert.addAction(submitAction)
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    
    present(alert, animated: true, completion: nil)
}

Explanation:

  • Shows an alert with a text field for user input.
  • Prints the entered name when Submit is tapped.

4. Creating an Action Sheet

func showActionSheet() {
    let actionSheet = UIAlertController(title: "Choose an Option", 
                                        message: nil, 
                                        preferredStyle: .actionSheet)

    let cameraAction = UIAlertAction(title: "Camera", style: .default) { _ in
        print("Camera selected")
    }
    
    let galleryAction = UIAlertAction(title: "Gallery", style: .default) { _ in
        print("Gallery selected")
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

    actionSheet.addAction(cameraAction)
    actionSheet.addAction(galleryAction)
    actionSheet.addAction(cancelAction)

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

Explanation:

  • Shows an Action Sheet at the bottom of the screen.
  • Allows users to pick an option like Camera or Gallery.
  • Cancelling dismisses the sheet.

5. Alert with a Countdown Timer

func showTimedAlert() {
    let alert = UIAlertController(title: "Auto-Dismiss", 
                                  message: "This will disappear in 3 seconds.", 
                                  preferredStyle: .alert)

    present(alert, animated: true)  
        
    // Dismiss after 3 seconds
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
        alert.dismiss(animated: true)
    }
}

Explanation:

  • The alert automatically disappears after 3 seconds.

6. Alert with Haptic Feedback (Vibration)

import AudioToolbox

func showHapticAlert() {
    let alert = UIAlertController(title: "Warning!", 
                                  message: "This action cannot be undone.", 
                                  preferredStyle: .alert)

    let confirmAction = UIAlertAction(title: "Proceed", style: .destructive) { _ in
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) // Vibrate on tap
    }

    alert.addAction(confirmAction)
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    
    present(alert, animated: true, completion: nil)
}

Explanation:

  • Uses haptic feedback (vibration) for warnings.

7. Alert Inside a Button Action

@IBAction func showAlertButtonTapped(_ sender: UIButton) {
    let alert = UIAlertController(title: "Hello!", message: "You tapped the button.", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    present(alert, animated: true, completion: nil)
}

Explanation:

  • Displays an alert when a button is tapped.

8. Summary of UIAlertController Features

FeatureCode Example
Simple AlertUIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
Action SheetUIAlertController(title: "Options", message: nil, preferredStyle: .actionSheet)
Multiple Buttonsalert.addAction(UIAlertAction(title: "OK", style: .default))
Text Inputalert.addTextField { textField in textField.placeholder = "Enter Name" }
Auto-Dismiss AlertDispatchQueue.main.asyncAfter(deadline: .now() + 3) { alert.dismiss(animated: true) }
Vibrating AlertAudioServicesPlaySystemSound(kSystemSoundID_Vibrate)

Conclusion

UIAlertController is a powerful and flexible way to interact with users. It is used for warnings, confirmations, text inputs, and action selections.

Would you like a customized alert design for a specific app feature? 🚀