【问题标题】:UIAlertViewStylePlainTextInput return key delegateUIAlertViewStylePlainTextInput 返回键委托
【发布时间】:2012-01-24 21:23:12
【问题描述】:

我正在为 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];

我现在使用的委托是:

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

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

提前致谢!

【问题讨论】:

    标签: iphone ios xcode ios5


    【解决方案1】:

    确保您的类符合<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];
    

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

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

    【讨论】:

    • 谢谢...每天编程 15 小时真的会让显而易见的事情被遗忘 ;-)
    • @jackslash 如果UIAlertView 不是属性,您能否在textFieldShouldReturn: 方法中解除父UIAlertView? (除了提升超级视图层次结构?)
    • @jackslash 另外,您应该使用self.scanCode.firstOtherButtonIndex 而不是0。并确保UIAlertView属性是弱引用,否则消失后会在内存中。
    • @zekel 我认为您需要将警报视图保留为属性,以便以编程方式将其关闭。您可以按照您的建议提升视图层次结构,但我更倾向于编写更清晰的代码并将其作为属性。我也同意使用弱属性是最好的方法,但是如果您要重用警报视图,则保留它与不保留它相比几乎没有什么惩罚,因为核心动画在其不在屏幕上时释放后备存储。跨度>
    猜你喜欢
    • 2012-04-07
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多