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

问题描述 投票:6回答:6

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

我的目的是使UISearchBar“X按钮”(qazxsw poi中的清除按钮)始终可见。

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

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

Code (Not working)

uitextfield

Goal:

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

  • 即如果我不输入任何文字。
ios iphone ios5 uibutton ios5.1
6个回答
5
投票

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

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

3
投票
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];

3
投票

这是搜索栏的默认行为。因为如果UITextField *searchBarTextField = nil; for (UIView *subview in self.searchBar.subviews) { if ([subview isKindOfClass:[UITextField class]]) { searchBarTextField = (UITextField *)subview; searchBarTextField.clearButtonMode = UITextFieldViewModeAlways; break; } } 是空白的,那么就没有必要按它。


0
投票

你可以在Xib中做到这一点。我正在附上截图。

并以编程方式

UITextField

0
投票

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

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

只需自己清除该字段并调用resignFirstResponder即可。

myUITextField.clearButtonMode = UITextFieldViewModeAlways;

有关它的文档-(BOOL)textFieldShouldClear:(UITextField *)textField { textField.text = @""; [textField resignFirstResponder]; return NO; }


0
投票

这是一个较老的问题,但我带来了一个平等的客户请求:“一旦光标在searchField中,就显示clearButton。我们希望能够在任何阶段使用此按钮取消搜索”。 除了添加自定义按钮之外,我想出了一个解决方案:

AppleDocs:

UITextFieldViewModeAlways如果文本字段包含文本,则始终显示叠加视图。

因此,添加一个空格作为第一个字符将使clearButton处于活动状态。 只要在searchField中输入文本或在使用文本之前的任何其他点,就可以删除前导空格。

HERE
© www.soinside.com 2019 - 2024. All rights reserved.