Quintin Balsdon Quintin Balsdon - 1 year ago 181
iOS Question

How to add TextField to UIAlertController in Swift

I am trying to show a UIAlertController with a UITextView. When I add the line:

//Add text field
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in

I get a Runtime error:

fatal error: unexpectedly found nil while unwrapping an Optional value

let alertController: UIAlertController = UIAlertController(title: "Find image", message: "Search for image", preferredStyle: .Alert)

//cancel button
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//cancel code

//Create an optional action
let nextAction: UIAlertAction = UIAlertAction(title: "Search", style: .Default) { action -> Void in
let text = (alertController.textFields?.first as! UITextField).text
println("You entered \(text)")

//Add text field
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.textColor = UIColor.greenColor()
//Present the AlertController
presentViewController(alertController, animated: true, completion: nil)

This is presented inside my ViewController via an IBAction.

I have downloaded the code from here: http://sourcefreeze.com/uialertcontroller-ios-8-using-swift/ and it works fine. I copied and pasted that method into my code and it breaks. The presence of self on the last line has no impact.

Answer Source

So I started checking to see what could possibly have been different in my code to the working code. I noticed that my ViewController extends


Which apparently means that I need to set the delegate of any child UITextView:

alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
        searchTextField = textField
        searchTextField?.delegate = self //REQUIRED
        searchTextField?.placeholder = "Enter your search terms"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download