UIAlertController is a class that display Alerts on the screen as per the different actions of the user. It is a class that replaces the UIAlertView && UIActionSheet. Alerts can be of any style like Destructive that will be shown when user did something awfully wrong && more. The action sheets can be shown differently based on the devices like on iPad it can be shown as Popover Controller. Basically on the controller you can add different actions with addAction() method. UIalertAction works with a completion handler in which you further can define other actions corresponding to the action that you will perform accordingly.
Here in this post I will show you how to add textFields to your UIActionController. So go ahead && add the following below written code to the viewDidLoad() method of the ViewController.Swift class:
Here all we are doing is instantiating the AlertViewController object that will present the alert view.And then adding to textfields to the alert box && then whatever user will type in those text fields will be printed not the console with the help of the Completion Handler.
Now to present the view of alert box with two textfields put the following line of code to the viewWillAppear() method of the ViewController.Swift file just after the viewDidLoad() method.
Output should be like this:
Here in this post I will show you how to add textFields to your UIActionController. So go ahead && add the following below written code to the viewDidLoad() method of the ViewController.Swift class:
override func viewDidLoad() {
super.viewDidLoad()
//instantiating an action controller
controller = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
//adding textFields to the Alert Box
controller?.addTextFieldWithConfigurationHandler({(textField: UITextField!) in textField.placeholder = "VVVVVVVVSSSSSSSSS"})
controller?.addTextFieldWithConfigurationHandler({(textField: UITextField!) in textField.placeholder = "VVVVVVVVSSSSSSSSS"})
//instantiating the action object that will display text what you write on the two text fields
let action = UIAlertAction(title: "Done", style: .Default, handler: {(paramAction: UIAlertAction!) in
if let textField = self.controller?.textFields {
let theTextFields = textField as [UITextField]
let userName = theTextFields[0].text + " " + theTextFields[1].text
println("Your username is \(userName)")
}
})
//adding action to the controller
controller?.addAction(action)
}
Now to present the view of alert box with two textfields put the following line of code to the viewWillAppear() method of the ViewController.Swift file just after the viewDidLoad() method.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//presenting the view of the alert box
self.presentViewController(controller!, animated: true, completion: nil)
}
Now input something in these textfields && then press done button you will see that whatever you entered in these textfields is printed on the console as well.