我正在尝试在我的一个页面中实现搜索栏。
由于其设计原因,我没有使用常规搜索栏。
我有如下。
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
如您所见,shouldBeginEditing
和 didBeginEditing
方法在清除后被调用,因此 textFieldshouldClear
中的 resignFirstResponder
在 shouldBeginEditing
或 didBeginEditing
调用新的 becomeFirstResponder
之前被调用。
关于objective-c - resignFirstResponder 没有在 textFieldShouldClear 中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24969140/