Alerts
UIAlertController displays an alert message in a small dialog box. Additionally you can associate an action with the alert controller.
let alert = UIAlertController.init(title: "Error",
message: "An unknown error has occurred",
preferredStyle: .alert)
let action = UIAlertAction.init(title: "Ok",
style: .default) { _ in
print("Ob button is pressed")
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
Show error message in controller
extension UIViewController {
func showErrorMessage(_ msg: String?) {
let alert = UIAlertController(title: "Error",
message:msg ?? "unknown error",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok",
style: UIAlertAction.Style.default,
handler: nil))
present(alert, animated: true, completion: nil)
}
func showAlert(_ msg: String?, title: String? = nil) {
let alert = UIAlertController(title: title ?? "Attention",
message:msg ?? "unknown error",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok",
style: .default,
handler: nil))
present(alert, animated: true, completion: nil)
}
}
The alert may contain one or more text fields that allow the user to enter some data.
Show prompt alert dialog
func showPromptAlert() {
let alert = UIAlertController(title: "Enter text",
message: nil,
preferredStyle: .alert)
alert.addTextField()
let action = UIAlertAction(title: "Done",
style: .default) { [unowned alert] _ in
let textField = alert.textFields![0]
// ...
}
alert.addAction(action)
present(alert, animated: true)
}