I'm trying to use the iOS 8 UIAlertController
in place of where I would have used a UIAlertView
in the past. I want the user to be able to enter text into this alert and hit "OK" to process the text or "Cancel" to cancel.
Here's the basic code:
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Change Value" message:@"Enter your new value."];
[alert addTextFieldWithConfigurationHandler:nil];
[alert addAction: [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
UITextField *textField = alert.textFields[0];
NSLog(@"text was %@", textField.text);
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
NSLog(@"Cancel pressed");
}]];
[presentingVC presentViewController:alert animated:YES completion:nil];
With the old UIAlertView
, I would tag it with an alertViewStyle
of UIAlertViewStylePlainTextInput
. Then, if the user hit the "Return" button on their keyboard after entering text, the UIAlertViewDelegate method willDismissWithButtonIndex:
would be called with some buttonIndex
(depending on what buttons had been specified in the UIAlertView
).
In the new UIAlertController
, if the user taps the "OK" or "Cancel" buttons, then their corresponding actions are performed as expected; but if the user just hits the "Return" key on the keyboard, it just hides the keyboard, but the alert remains on screen and no action is performed.
I've thought about configuring the text field to set the UITextFieldDelegate
to self
, and then maybe overriding the textFieldDidReturn:
method, but I also don't know if there's a way to call one of the UIAlertController
's actions programmatically. And this is sounding sort of messy/hacky anyway. Am I missing something obvious?
On iOS 9.3, this happens when you have multiple actions with UIAlertActionStyleDefault
style.
When you add one action with UIAlertActionStyleDefault
and another one withUIAlertActionStyleCancel
, the action with default style will be called
This is an old question, but there's been a simple solution around since iOS9 that I didn't see listed here, so hopefully this will help others.
It is true, that when you have multiple UIAlertActionStyleDefault
actions, the system can't choose which one to trigger when the user presses the enter key in the UITextField
.
However, you can set the preferredAction
property on the UIAlertController to remedy this.
Therefore:
myAlertController.preferredAction = myDefaultAction;
Pressing enter in the UITextField will now trigger your chosen UIAlertAction.
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