xcode UIAlertViewStylePlainTextInput 返回键委托

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8994368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 23:05:12  来源:igfitidea点击:

UIAlertViewStylePlainTextInput return key delegate

iphoneiosxcodeios5

提问by CyberK

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

我正在为 UIAlertView 使用新的 iOS 5 功能之一。我像这样创建了一个 UIAlertView:

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?

现在我想模拟回车键,所以当用户按下键盘上的返回键时,按下警报的 OK 按钮时会发生同样的事情。我怎样才能做到这一点?

Thanks in advance!

提前致谢!

回答by Hymanslash

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

确保您的类符合<UITextFieldDelegate>协议,UIAlertView为您的类创建一个属性并将以下行添加到您的设置代码中...

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:

通过成为输入文本字段的代理,您可以知道何时按下键盘上的返回键。然后在您的类的 .m 文件中实现下面的委托方法并告诉警报消失:

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.scanCode dismissWithClickedButtonIndex:self.scanCode.firstOtherButtonIndex animated:YES];
    return YES;
}