Since iOS 9, UIAlertController
has a property called preferredAction
. preferredAction
has the following declaration:
var preferredAction: UIAlertAction? { get set }
The preferred action for the user to take from an alert. [...] The preferred action is relevant for the UIAlertController.Style.alert
style only; it is not used by action sheets. When you specify a preferred action, the alert controller highlights the text of that action to give it emphasis. (If the alert also contains a cancel button, the preferred action receives the highlighting instead of the cancel button.) [...] The default value of this property is nil
.
The Swift 5 / iOS 12 sample code below shows how to display a UIAlertController
that will highlight the text of a specified UIAlertAction
using preferredAction
:
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let okAction = UIAlertAction(title: "OK", style: .default, handler: { action in
print("Hello")
})
alertController.addAction(cancelAction)
alertController.addAction(okAction)
alertController.preferredAction = okAction
present(alertController, animated: true, completion: nil)