objective-c - resignFirstResponder 没有在 textFieldShouldClear 中被调用

标签 objective-c ios7 uitextfield uitextfielddelegate

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

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

我有如下。

UIImageView above UIView (textfield background)
UITextField above UIImageView (textfield)

我正在为 UITextField 使用 delegates

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

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

我有以下代码

- (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;
}

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

知道为什么当我有时键盘没有被关闭


编辑1

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

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

最佳答案

除了我的评论之外,我还进行了一些测试,这是我的结果:

我刚刚使用如下所有委托(delegate)方法实现了一个 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;
}

一旦您点击清除按钮,日志输出:

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

如您所见,shouldBeginEditingdidBeginEditing 方法在清除后被调用,因此 textFieldshouldClear 中的 resignFirstRespondershouldBeginEditingdidBeginEditing 调用新的 becomeFirstResponder 之前被调用。

关于objective-c - resignFirstResponder 没有在 textFieldShouldClear 中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24969140/

相关文章:

ios - iOS 7 UIAlertView按钮不可见

iphone - 数字布局在安全的 UITextField 中不粘?

objective-c - 数据格式化程序暂时不可用,将在继续后重试

objective-c - 如何根据他们选择的上一个 View 中的哪个单元格自定义用户看到的 UITableView?

ios - 为什么不对所有 Core Data 操作使用私有(private)上下文?

ios - 检查 UITextField 可见但在键盘后面

ios - 更改焦点上的文本字段

ios - 弱属性的大量开销?

ios - 将整数值从一个 ViewController 传递到另一个 ViewController 并将其显示在 UITextField 中

ios - native Controller 的 preferredStatusBarStyle