UIAlertController with text field - hitting return button only hides keyboard, does not perform action?

UberJason picture UberJason · Sep 25, 2014 · Viewed 9.2k times · Source

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?

Answer

lukas picture lukas · Mar 23, 2016

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