IOS provides two constant values:
.alert
-
.actionSheet
.alert
@IBAction func alertCalled(_ sender: Any) {
let alert = UIAlertController(title: "Delete Message", message: "Are you sure you want to delete this message?", preferredStyle: .alert)
// two buttons
let cancelAction = UIAlertAction(title: "No", style: .cancel)
let yesAction = UIAlertAction(title: "Yes", style: .destructive) { _ in
print("message deleted!")
}
// add action to the alert
alert.addAction(yesAction)
alert.addAction(cancelAction)
self.present(alert, animated: true)
}
.actionSheet
@IBAction func alertCalled(_ sender: Any) {
let alert = UIAlertController(title: "Delete Message!", message: "Are you sure you want to delete this message?", preferredStyle: .actionSheet)
// two buttons
let cancelAction = UIAlertAction(title: "No", style: .cancel)
let yesAction = UIAlertAction(title: "Yes", style: .destructive) { _ in
print("message deleted!")
}
// add action to the alert
alert.addAction(yesAction)
alert.addAction(cancelAction)
self.present(alert, animated: true)
}
AlertControllers accepting user input
NOTE: you CANNOT use .actionSheet
with addTextField()
method
@IBAction func alertWithTextFieldCalled(_ sender: Any) {
let alert = UIAlertController(title: "Hello", message: "What is your name?", preferredStyle: .alert)
alert.addTextField() { textField in
textField.placeholder = "Enter your name"
}
// two buttons
let cancelAction = UIAlertAction(title: "No", style: .cancel)
let yesAction = UIAlertAction(title: "Yes", style: .destructive) { _ in
let textField = alert.textFields![0] as UITextField
guard let name = textField.text else {
return
}
print("Hello \(name)")
}
// add action to the alert
alert.addAction(yesAction)
alert.addAction(cancelAction)
self.present(alert, animated: true)
}
Top comments (0)