4

I'm trying to get a textField value from UIAlertController, but whenever I try to enter the value and try to print it out, the output doesn't show anything.

code:

var alert = UIAlertController(title: "Enter the password", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
                textField.placeholder = "Enter text:"
                textField.secureTextEntry = true
                println(textField.text)

      })
self.presentViewController(alert, animated: true, completion: nil
Mike T
  • 4,747
  • 4
  • 32
  • 52
sinusGob
  • 4,053
  • 12
  • 46
  • 82

1 Answers1

10

Try this code :

var inputTextField: UITextField?
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
    // Do whatever you want with inputTextField?.text
    println("\(inputTextField?.text)")
})

let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in
}
alertController.addAction(ok)
alertController.addAction(cancel)
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
    inputTextField = textField
}
presentViewController(alertController, animated: true, completion: nil)
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136