如何在uisearchbar中显示Xbutton(清除按钮)始终可见

在我的应用程序中,我添加了一个UISearchBar 。

我的目的是使UISearch栏“X按钮”( UITextField中的清除按钮)始终可见。

我尝试使用下面的代码尝试使“X按钮”始终可见。 但是,它不起作用。 如果我设置tf.clearButtonMode = UITextFieldViewModeNever ,则uitextfield中的clear按钮不显示。 我不确定有什么问题?

我真的很感激任何人的帮助。 为什么这不起作用?

代码(不工作)

 for (UIView* v in searchBar.subviews) { if ( [v isKindOfClass: [UITextField class]] ) { UITextField *tf = (UITextField *)v; tf.delegate = self; tf.clearButtonMode = UITextFieldViewModeAlways; break; } } 

目标:

如果文本长度等于0,我想始终显示清除按钮

  • 即如果我不输入任何文字。

您需要为清除按钮创建自定义UIButton

 UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom]; [clearButton setImage:img forState:UIControlStateNormal]; [clearButton setFrame:frame]; [clearButton addTarget:self action:@selector(clearTextField:) forControlEvents:UIControlEventTouchUpInside]; textField.rightViewMode = UITextFieldViewModeAlways; //can be changed to UITextFieldViewModeNever, UITextFieldViewModeWhileEditing, UITextFieldViewModeUnlessEditing [textField setRightView:clearButton]; 
 UITextField *searchBarTextField = nil; for (UIView *subview in self.searchBar.subviews) { if ([subview isKindOfClass:[UITextField class]]) { searchBarTextField = (UITextField *)subview; searchBarTextField.clearButtonMode = UITextFieldViewModeAlways; break; } } 

这是搜索栏的默认行为。 因为如果UITextField为空,则无需按下它。

你可以在Xib中做到。 我附上截图。

在此处输入图像描述

并以编程方式

 myUITextField.clearButtonMode = UITextFieldViewModeAlways; 

我试图得到它但不幸的是,没有使用UITextField的ClearButton(X)进行自定义的方法。

有一种方法,如果您只需要它来重新签名KeyBoard,那么只需覆盖此方法:

只需自己清理该字段并调用resignFirstResponder。

 -(BOOL)textFieldShouldClear:(UITextField *)textField { textField.text = @""; [textField resignFirstResponder]; return NO; } 

关于它的文档在这里