Modularized, Customizable Alerts in Swift
In iOS Development, it is frequently required to provide alerts to users. This is a code snippet that I developed that I now use in all of my applications. Feel free to use and adapt it to your needs.
import UIKit
/** Easily Create, Customize, and Present an UIAlertController on a UIViewController
- Parameters:
- target: The instance of a UIViewController that you would like to present the UIAlertController upon.
- title: The `title` for the UIAlertController.
- message: Optional `message` field for the UIAlertController. nil by default
- style: The `preferredStyle` for the UIAlertController. UIAlertControllerStyle.alert by default
- actionList: A list of `UIAlertAction`. If no action is added, `[UIAlertAction(title: "OK", style: .default, handler: nil)]` will be added.
*/
func showAlert(target: UIViewController, title: String, message: String? = nil, style: UIAlertControllerStyle = .alert, actionList:[UIAlertAction] = [UIAlertAction(title: "OK", style: .default, handler: nil)] ) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
for action in actionList {
alert.addAction(action)
}
// Check to see if the target viewController current is currently presenting a ViewController
if target.presentedViewController == nil {
target.present(alert, animated: true, completion: nil)
}
}
}
subscribe via RSS
Unless otherwise mentioned in the post, all projects are side projects which I work on in my freetime on weekends and evenings, and are not affiliated with my work or employer.
All views and opinions are my own.