Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close UIAlertView with press of Return key on external keyboard

I am showing a simple alert view like this:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"title" message:@"msg" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];

Now, if the user has an external (bluetooth) keyboard attached, I want to close the alert dialog if the user types the Return key.

How do I accomplish that?

The challenge here is to learn of the press of any key on the keyboard. Once that's know, dismissing the dialog is trivial (with [UIAlertView dismissWithClickedButtonIndex:...]).

I've tried to implement the [UIViewController keyCommands function, returning a handler for "\r", but that only works while my main view shows, not while the alert is showing.

You can view a sample project here: https://github.com/tempelmann/AlertViewReturnKeyDismissal

Note: So far, the two posted solutions below do NOT work in general, but only if the alert is shown from within viewDidLoad. I need this to work when I show the alert past viewDidLoad, though.

like image 344
Thomas Tempelmann Avatar asked May 09 '14 14:05

Thomas Tempelmann


1 Answers

The following worked for me...

First set the view controller that is handling the alert view to the first responder with:

[self becomeFirstResponder];

Next be sure to override the following methods on your view controller:

- (BOOL)canBecomeFirstResponder {
    return YES;
}

-(NSArray *)keyCommands {
    return @[[UIKeyCommand keyCommandWithInput:@"\r" modifierFlags:0 action:@selector(enterPressed)]];
}

Then after displaying your alert view, since the view controller will still be the first responder, you can simply have your enterPressed method dismiss the alert view:

-(void)enterPressed {
    [self.alert dismissWithClickedButtonIndex:0 animated:YES];
}
like image 99
Kevin DiTraglia Avatar answered Oct 20 '22 00:10

Kevin DiTraglia