简体   繁体   中英

How do you use an alert to prompt for text in iOS with 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM