resignFirstResponder 没有在 textFieldShouldClear 内被调用

Fah*_*kar 3 objective-c uitextfield uitextfielddelegate ios7

我正在尝试在我的页面之一中实现搜索栏。

由于其设计,我没有使用常规搜索栏。

我所拥有的如下。

UIImageView above UIView (textfield background)
UITextField above UIImageView (textfield)
Run Code Online (Sandbox Code Playgroud)

我正在使用delegatesfor UITextField

在代码中,我必须searchTF.clearButtonMode = UITextFieldViewModeWhileEditing;显示清除按钮。

搜索工作正常,但问题出在清除按钮的委托中。

我有以下代码

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == searchTF) {

        NSLog(@"clicked clear button");
        [textField resignFirstResponder]; // this is not working
        // also below is not working
        // [searchTF resignFirstResponder];
    }

    return YES;
}
Run Code Online (Sandbox Code Playgroud)

当我点击清除按钮时,我得到文本“点击清除按钮”的 NSLog,但是键盘没有被解除。

知道为什么当我有键盘时没有被解雇


编辑 1

即使我尝试如下使用[self.view endEditing:YES];,但仍然无法正常工作。

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == searchTF) {
        [self.view endEditing:YES];
        [self hideAllKeyboards];
    }
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*iel 5

除了我的评论之外,我还做了一些测试,以下是我的结果:

我刚刚UITextField用这样的所有委托方法实现了一个:

- (BOOL)textFieldShouldClear:(UITextField *)textField {
  NSLog(@"Should Clear");
  [textField resignFirstResponder];
  return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
  NSLog(@"Begin editing");
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
  NSLog(@"End editing");
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
  NSLog(@"Should begin editing");
  return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
  NSLog(@"Should end editing");
  return YES;
}

- (BOOL)textField:(UITextField *)textField
    shouldChangeCharactersInRange:(NSRange)range
                replacementString:(NSString *)string {
  NSLog(@"Change char");
  return YES;
}
Run Code Online (Sandbox Code Playgroud)

只要您点击清除按钮,日志就会输出:

2014-07-26 11:08:44.558 Test[36330:60b] Should Clear
2014-07-26 11:08:44.558 Test[36330:60b] Should end editing
2014-07-26 11:08:44.559 Test[36330:60b] End editing
2014-07-26 11:08:44.560 Test[36330:60b] Should begin editing
2014-07-26 11:08:44.561 Test[36330:60b] Begin editing
Run Code Online (Sandbox Code Playgroud)

正如您所看到的shouldBeginEditingdidBeginEditing方法在清除后被调用,因此resignFirstResponderintextFieldshouldClear在 newbecomeFirstRespondershouldBeginEditingor调用之前被调用didBeginEditing

  • 嗯,我认为您解决问题的方式更像是一种解决方法,因为您的计时器可能比委托方法更快,例如在较慢的设备上。更好的解决方案是像这样实现 `textFieldShouldClear` `[textField resignFirstResponder];` `textField.text = @"";` `return NO;` (2认同)