How do you use a warning to request text in iOS using 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 are trying to create an alert to request a name. We get the error "EXC_BAD_INSTRUCTION" in the line alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in.

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

+4
source share
1 answer

You get the text field 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 displayed error occurs in a place other than the value indicated in the error message.

+4
source

Source: https://habr.com/ru/post/1547211/


All Articles