How to get textField value in UIAlertController?

I'm trying to get the value of a textField from a UIAlertController, but whenever I try to enter a value and try to print it, 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

      

+3


source to share


1 answer


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)

      

+6


source







All Articles