Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use an alert to prompt for text in iOS with Swift?

Tags:

ios

swift

func addPitcher(sender: UIBarButtonItem) {
    var alert = UIAlertController(title: "New Pitcher", message: "Enter Name", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Finish", style: UIAlertActionStyle.Default, handler: nil))
    alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Name"
        textField.secureTextEntry = false
    })
    self.presentViewController(alert, animated: true, completion: nil)
    let newName : String = alert.textFields[0] as String
    println(newName)
}

This is the function in which we try and create an alert to prompt for a name. We get "EXC_BAD_INSTRUCTION" error at the alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in line.

How do we fix this error, or more importantly, how do we retrieve the text from the field? Thank you for all help.

like image 395
barsoft Avatar asked Jul 04 '14 18:07

barsoft


1 Answers

You're getting a textfield as a string. Blammo.

Also, get the value in the handler.

alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler:{ (alertAction:UIAlertAction!) in
            let textf = alert.textFields[0] as UITextField
            println(textf.text)
            }))

ps sometimes the error shown happens in a location different from the one given in the error message.

like image 197
Gene De Lisa Avatar answered Sep 22 '22 01:09

Gene De Lisa