/ SWIFT

Creating Reusable UIAlertController

The basic method of presenting alert messages to user is by means of UIAlertController. It’s common to show the same alerts in different parts of your app. To avoid duplication we can create factory methods for each alert configuration.

This is how we can declare a new alert:

extension UIAlertController {
    static func signOutConfirmation(onConfirm: @escaping () -> Void) -> UIAlertController {
        let ok = UIAlertAction(title: "OK", style: .default) { _ in onConfirm() }
        let cancel = UIAlertAction(title: "Cancel", style: .cancel)
        
        let alert = UIAlertController(title: nil, message: "Are you sure?", preferredStyle: .alert)
        alert.addAction(ok)
        alert.addAction(cancel)
        
        return alert
    }
}

Here is how we can present the alert:

let source = UIViewController()
let alert = UIAlertController.signOutConfirmation { print("Signed out") }
source.present(alert, animated: true)

This approach cuts boilerplate code, organizes your alerts in one place and makes them more readable.


Thanks for reading!

If you enjoyed this post, be sure to follow me on Twitter to keep up with the new content. There I write daily on iOS development, programming, and Swift.

Vadim Bulavin

Creator of Yet Another Swift Blog. Coding for fun since 2008, for food since 2012.

Follow