【问题标题】:ios Keyboard must not show up automatically for a UITextField in UIAlertControllerios 键盘不能自动显示在 UIAlertController 中的 UITextField
【发布时间】:2018-03-03 12:50:36
【问题描述】:

我正在尝试使用文本字段显示 UIAlertController。当它启动时,键盘会自动显示为文本字段,自动获得焦点。如何在没有键盘的情况下显示带有文本字段的警报(它应该仅在用户单击文本字段时显示)。

这是我的代码

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Collect Input"    message:@"input message"
    preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"Submit" style:UIAlertActionStyleDefault
    handler:^(UIAlertAction * action) {
        //use alert.textFields[0].text
    }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" handler:^(UIAlertAction * action) {
    //cancel action
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
         // A block for configuring the text field prior to displaying the alert
         //[textField resignFirstResponder];

    }];
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:NO completion:nil];

【问题讨论】:

  • 首先想到的是在配置处理程序中 setUserInteractionEnabled = false 并立即执行 dispatch_async() 以重新启用它。如果做不到这一点,则 dispatch_async() 会退出第一响应者
  • 文本字段/文本视图在成为第一响应者时显示键盘。最有可能的是,警报控制器是由于被呈现而导致的。您可以像@ekscripto 建议的那样暂时禁用用户交互。

标签: ios objective-c keyboard uialertcontroller


【解决方案1】:

有几个解决方案。

  1. 您可以在addTextFieldWithConfigurationHandler 回调中获取对文本字段的引用并将其存储在局部变量中。然后在presentViewController 的完成处理程序中,您可以在文本字段上调用resignFirstResponder。但这种解决方案远非理想,因为键盘会出现然后立即消失。

  2. 更好的是设置文本字段的delegate 并实现shouldBeginEditing 委托方法。添加一个实例变量作为标志。第一次调用shouldBeginEditing,不是没有设置标志,设置它,然后返回NO。然后每次之后,检查标志并返回YES

这是选项 2 的实现:

表明你的类符合 .m 文件中的UITextFieldDelegate 协议:

@interface YourClassHere () <UITextFieldDelegate>
@end

为标志添加一个实例变量:

BOOL showKeyboard = NO;

更新您的警报设置代码以设置文本字段的委托:

[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    textField.delegate = self;
}];

实现文本字段委托方法:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (showKeyboard) {
        return YES;
    } else {
        showKeyboard = YES;
        return NO;
    }
}

这会阻止键盘的初始显示,但在此之后的任何时间都允许。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-20
    • 2015-12-15
    • 1970-01-01
    • 2013-02-14
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多