How to add a TextField to UIAlertView in Swift
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 = ...
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
In Objective C
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Duplicate file" message:@"A file with the same name already exists." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; alertView.alertViewStyle = UIAlertViewStylePlainTextInput; [[alertView textFieldAtIndex:0] setText:@"Filename"]; [[alertView textFieldAtIndex:0] setPlaceholder:@"Enter Filename"]; [alertView show];
In Swift 2.3
func doSomething(){ var alert = UIAlertController(title: "Duplicate file", message: "A file with the same name already exists.", preferredStyle: UIAlertControllerStyle.Alert) alert.addTextFieldWithConfigurationHandler(configurationTextField) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction)in print("User click Ok button") print(self.textField.text) })) self.presentViewController(alert, animated: true, completion: { print("completion block") })} func configurationTextField(textField: UITextField!){ textField.text = "Filename" }
In Swift 3
func doSomething(){ var alert = UIAlertController(title: "Duplicate file", message: "A file with the same name already exists.", preferredStyle: UIAlertControllerStyle.alert) alert.addTextField(configurationHandler: configurationTextField) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:{ (UIAlertAction)in print("User click Ok button") print(self.textField.text) })) self.present(alert, animated: true, completion: { print("completion block") })}func configurationTextField(textField: UITextField!){ textField.text = "Filename"}