It's convenient and useful because you don't have to arrange the UI each time you want to enter something.
Completed form
Xcode 12.3
let title = "Title"
let msg = "Message"
let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
//OK button settings
let okAction = UIAlertAction(title: "OK", style: .default, handler: {(action:UIAlertAction!) -> Void in
//What to do when the OK button is pressed in an alert with a text field
//Optional binding and retrieval of the value entered in the text field
if let str = alert.textFields?[0].text{
print(str)
}
})
alert.addAction(okAction)
//Cancel button settings
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancelAction)
//Add text field
alert.addTextField(configurationHandler: {(textField:UITextField!) -> Void in
//You can customize the text field here
textField.placeholder = ""
textField.keyboardType = .default
})
//If you want to add more than one, write that number
// alert.addTextField(configurationHandler: {(textField: UITextField!) -> Void in
// textField.placeholder = "text"
// })
//Display alerts on screen
self.present(alert, animated: true, completion: nil)
}
If you want to use multiple textFields, write multiple addTextFields