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

ban*_*anu 6 iphone uibutton ios ios5 ios5.1

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

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

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

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

代码(不工作)

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

目标:

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

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

Rus*_*abh 5

您需要为清除按钮创建自定义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];
Run Code Online (Sandbox Code Playgroud)


Sah*_*jan 1

你可以在西安做。我附上屏幕截图。

在此输入图像描述

并以编程方式

myUITextField.clearButtonMode = UITextFieldViewModeAlways;
Run Code Online (Sandbox Code Playgroud)

  • 提出这个问题的人对“始终”的概念感到非常困难。 (2认同)