Obtaining Text Inputs
In addition to displaying messages, you can use the UIAlertController class to obtain text inputs. For example, the following code snippet uses the UIAlertController class to ask the user to enter an email address:
var alertController = UIAlertController( title: "Email", message: "Please enter your email", preferredStyle: UIAlertControllerStyle.Alert) var okAction = UIAlertAction( title: "OK", style: UIAlertActionStyle.Default) { (action) -> Void in println( "You entered \((alertController.textFields?.first as UITextField).text)") } alertController.addTextFieldWithConfigurationHandler { (txtEmail) -> Void in txtEmail.placeholder = "<Your email here>" } alertController.addAction(okAction) self.presentViewController(alertController, animated: true, completion: nil)
Figure 6 shows the alert with the text-input field.
Figure 6 The UIAlertController class displays a text-input field.
To add a text-input field to the UIAlertController class, use the addTextFieldWithConfigurationHandler() method. This method takes in a closure with an input parameter representing the UITextField:
alertController.addTextFieldWithConfigurationHandler { (txtEmail) -> Void in txtEmail.placeholder = "<Your email here>" }
When the alert is dismissed, you can obtained the text entered by the user through the textFields property, which contains an array of UITextField objects:
"You entered \((alertController.textFields?.first as UITextField).text)")
The first property returns the first UITextField in the array, which in this example contains the email address entered by the user.
If you want multiple text fields, call the addTextFieldWithConfigurationHandler() method again:
alertController.addTextFieldWithConfigurationHandler { (txtEmail) -> Void in txtEmail.placeholder = "<Your email here>" } alertController.addTextFieldWithConfigurationHandler { (txtPassword) -> Void in txtPassword.secureTextEntry = true txtPassword.placeholder = "<Your password here>" }
Figure 7 shows the alert, which asks the user to enter an email address and a password.
Figure 7 Multiple text inputs in an alert.
To obtain the password that the user entered, you just need to access the second element in the array:
alertController.textFields?[1] as UITextField).text