In my application I want a alert with a textfield. After clicking on "Done" I want to save the textfield input in a String. After clicking on "Cancel" I want only to close the alert. I've created my alert like this:
var alert = UIAlertView()
alert.title = "Enter Input"
alert.addButtonWithTitle("Done")
alert.alertViewStyle = UIAlertViewStyle.PlainTextInput
alert.addButtonWithTitle("Cancel")
alert.show()
let textField = alert.textFieldAtIndex(0)
textField!.placeholder = "Enter an Item"
println(textField!.text)
The alert looks like this:
I want to know how to get the text from the textfield, and how to create events for the "Done" button and the "Cancel" button.
You may go with UIAlertController instead of UIAlertView.
I've already implemented and tested too using UIAlertController for what you actually want. Please try the following code
var tField: UITextField!
func configurationTextField(textField: UITextField!)
{
print("generating the TextField")
textField.placeholder = "Enter an item"
tField = textField
}
func handleCancel(alertView: UIAlertAction!)
{
print("Cancelled !!")
}
var alert = UIAlertController(title: "Enter Input", message: "", preferredStyle: .Alert)
alert.addTextFieldWithConfigurationHandler(configurationTextField)
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler:handleCancel))
alert.addAction(UIAlertAction(title: "Done", style: .Default, handler:{ (UIAlertAction) in
print("Done !!")
print("Item : \(self.tField.text)")
}))
self.presentViewController(alert, animated: true, completion: {
print("completion block")
})
You will have to implement the UIAlertViewDelegate's
optional func alertView(_ alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int)
For SWIFT 3
@IBAction func ForgotPassword(_ sender: Any) {
let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .alert)
let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in
if let field = alertController.textFields![0] as? UITextField {
// store and use entered data
} else {
print("please enter email id")
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }
alertController.addTextField { (textField) in
textField.placeholder = "Email"
}
alertController.addAction(confirmAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
I hope it will help someone else :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With