Skip to content

Instantly share code, notes, and snippets.

@cumanzor
Created December 5, 2018 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cumanzor/ac23c592413d709c95e1510c52c32c62 to your computer and use it in GitHub Desktop.
Save cumanzor/ac23c592413d709c95e1510c52c32c62 to your computer and use it in GitHub Desktop.
[Show simple UIAlerts from any VC] #ios #swift
extension UIViewController {
func showAlert(withTitle title: String, message : String, withActions actions:[UIAlertAction] = [], withCompletion c:(()->())?=nil) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
if actions.isEmpty{ // default ok action
let defaultAction = UIAlertAction(title: "Ok", style: .default)
alertController.addAction(defaultAction)
}
for action in actions{
alertController.addAction(action)
}
self.present(alertController, animated: true, completion: c)
}
}
// use it like this:
// show a simple message with an ok action that just dismisses the alert
showAlert(withTitle: "Error", message: "Unable to do stuff.")
// add an action (pop the VC)
let backAction = UIAlertAction(title: "Ok", style: .default) { (action) in
self.navigationController?.popViewController(animated: true)
}
showAlert(withTitle: "Error", message: "Unable to do stuff, please return and try again.", withActions: [backAction])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment