I have various controllers in my app that all require validation, and when validation fails, I want to display an alert with the errors. Is there some best practice/design pattern for doing this? I could simply create a static function in a Helper class like so:
static func displayAlert(message: String, buttonTitle: String, vc: UIViewController) { let alertController = UIAlertController(title: "", message: message, preferredStyle: .Alert) let okAction = UIAlertAction(title: buttonTitle, style: .Default, handler: nil) alertController.addAction(okAction) vc.presentViewController(alertController, animated: true, completion: nil) }
But then I need to pass the view controller..which seems like bad practice. I could shoot off a notification and observe it, but that seems like overkill. Am I overthinking this, or is there some more acceptable way to go about handling something like this?
I ended up creating an extension for UIViewController and creating the alert function there:
extension UIViewController { func alert(message: String, title: String = "") { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(OKAction) self.present(alertController, animated: true, completion: nil) } }
Swift 4
I wanted this same functionality for myself, so I made a full extension. To use it, create a new swift file in your project and name it whatever you'd like. Place the following code inside:
import UIKit extension UIViewController { func presentAlertWithTitle(title: String, message: String, options: String..., completion: @escaping (Int) -> Void) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) for (index, option) in options.enumerated() { alertController.addAction(UIAlertAction.init(title: option, style: .default, handler: { (action) in completion(index) })) } self.present(alertController, animated: true, completion: nil) } }
To use it (which so many people don't actually show, which can lead to confusion for a newbie like myself):
presentAlertWithTitle(title: "Test", message: "A message", options: "1", "2") { (option) in print("option: \(option)") switch(option) { case 0: print("option one") break case 1: print("option two") default: break } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With