totoajax totoajax - 2 years ago 103
Swift Question

How to get input value from TextField in iOS alert

I'm trying to make an alert message with input, and then get the value from the input. I've found many good tutorials how to make the input text field. but I can't get the value from the alert.

Does someone have an example code? I would appraise that!

Answer Source

Assuming you want an action alert on iOS:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download