Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIAlertViewStylePlainTextInput return key delegate

I'm using one of the new iOS 5 features for a UIAlertView. I create a UIAlertView like this:

UIAlertView *scanCode = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Some Title", @"") message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:NSLocalizedString(@"OK", @""), nil];
        [scanCode setAlertViewStyle:UIAlertViewStylePlainTextInput];
        scanCode.tag = 1234;
        [scanCode show];
        [scanCode release];

The delegate I use now is:

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 1234) {
        if (buttonIndex == 1)
        {
            //do something
            }
        }
    }
}

Now I want to simulate the enter key, so when the user hits return on the keyboard the same thing happens when pressing the OK button of the alert. How can I do this?

Thanks in advance!

like image 863
CyberK Avatar asked Jan 24 '12 21:01

CyberK


1 Answers

Make sure your class conforms to the <UITextFieldDelegate> protocol, make the UIAlertView a property for your class and add the following line to your setup code...

self.scanCode = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Some Title", @"") message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:NSLocalizedString(@"OK", @""), nil];
[self.scanCode setAlertViewStyle:UIAlertViewStylePlainTextInput];
self.scanCode.tag = 1234;
//add this...
[[self.scanCode textFieldAtIndex:0] setDelegate:self];
[self.scanCode show];

By becoming the delegate for the input text field you can find out when the return key on the keyboard is pressed. Then in the .m file for your class you implement the delegate method below and tell the alert to disappear:

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.scanCode dismissWithClickedButtonIndex:self.scanCode.firstOtherButtonIndex animated:YES];
    return YES;
}
like image 86
jackslash Avatar answered Oct 28 '22 15:10

jackslash