How to add a TextField to UIAlertView in Swift

Try This Code (with swift):

func configurationTextField(textField: UITextField!)
    {
        println("configurat hire the TextField")

        if let tField = textField {

            self.textField = textField!        //Save reference to the UITextField
            self.textField.text = "Hello world"
        }
    }


 func handleCancel(alertView: UIAlertAction!)
        {
           println("User click Cancel button") 
           println(self.textField.text)
        }

 var alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.Alert)

    alert.addTextFieldWithConfigurationHandler(configurationTextField)

    alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:handleCancel))
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in
            println("User click Ok button")
            println(self.textField.text)
        }))
    self.presentViewController(alert, animated: true, completion: {
            println("completion block")
        })

Can you see also my answer here


You can access the textfield with:

let textField = alert.textFieldAtIndex(0)

Then to change the placeholder text:

textField.placeholder = "Foo!"

And the keyboard type:

textField.keyboardType = ...