【问题标题】:iOS Keyboard won't dismissiOS 键盘不会关闭
【发布时间】:2015-12-19 11:20:30
【问题描述】:

我的视图控制器上有一个带有文本字段的表单。当用户触摸文本字段以添加他们的状态时,我会显示一个 UIPicker 供他们选择一个。问题是如果键盘是从以前的文本字段中显示的,我无法将其关闭。这是我的代码:

- (void) textFieldDidBeginEditing:(UITextField *)textField {

    if (self.currentTextField) {
        self.currentTextField = nil;
        self.currentTextField = (KIP_TextField*)textField;
    } else {
        self.currentTextField = (KIP_TextField*)textField;
    }


    if (self.currentTextField.tag == 0 || self.currentTextField.tag == self.arrSearchFields.count-1) {

        //kill the editing
        [self.view endEditing:YES];
        [self.currentTextField resignFirstResponder];

        //set the picker type
        if (self.currentTextField.tag == 0) {
            self.currentPickerType = SUPPLIER_PICKER;
        } else if (self.currentTextField.tag == self.arrSearchFields.count-1) {
            self.currentPickerType = STATE_PICKER;
        }

        if (!self.hasPicker) {
            [self addPicker];
        } else {
            [self closePicker:YES];
        }

    } else {
        [self closePicker:NO];
    }

}

对于那些用 resignFirstResponder 回复的人:我有它并且它可以工作,但是当我显示选择器时我需要关闭键盘。因此,对于 TF1 和 2,有 3 个文本字段 TF1、TF2、TF3,触摸它们会启动一个选择器,当用户选择一个选择器行时,文本字段会填充该值并关闭选择器。但是,如果您先进入 TF2,则会显示键盘,您可以通过返回键将其关闭,否则 texfieldDidEndEditing 将关闭它。但是假设您不输入任何文本而是触摸 TF1 或 3,现在会显示选择器但键盘仍在屏幕上。即使使用 self.view endEditing,我也无法将其关闭

【问题讨论】:

标签: ios keyboard uitextfield


【解决方案1】:

在尝试关闭键盘时,对 UITextView 使用以下委托方法:

- (BOOL)textFieldShouldReturn:(UITextField*)textField {
    [textField resignFirstResponder];
    return NO;
}

确保添加委托

emailTextField.delegate = self

您应该在实现选择器之前实现这一点。

【讨论】:

    【解决方案2】:

    您可以使用 textFieldShouldReturn 委托方法:

    - (BOOL)textFieldShouldReturn:(UITextField*)textField 
    {
        [textField resignFirstResponder];
        return NO;
    }
    

    如果您有多个文本字段并且不知道哪个是第一响应者(或者您根本无法从编写此代码的任何位置访问文本字段),您可以在包含的父视图上调用 endEditing:文本字段。

    [[self view] endEditing:YES];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多