Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show Xbutton(clear button) always visible in uisearchbar [duplicate]

In my application, I am adding a UISearchBar.

My intent is to enable the UISearch Bar "X button"(clear button in UITextField) to be always visible.

I have tried using the following code below to try to make the "X Button" be always visible. However, it does not work. If I set tf.clearButtonMode = UITextFieldViewModeNever, the clear button in uitextfield not showing. I am not sure what is wrong?

I would really appreciate anyone's help here. Why is this not working?

Code (Not working)

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

Goal:

I want to always show the clear button if the text length is equal to 0

  • i.e. if I don't input any text.
like image 576
banu Avatar asked Aug 13 '13 11:08

banu


3 Answers

UITextField *searchBarTextField = nil;
    for (UIView *subview in self.searchBar.subviews)
    {
        if ([subview isKindOfClass:[UITextField class]])
        {
            searchBarTextField = (UITextField *)subview;
            searchBarTextField.clearButtonMode = UITextFieldViewModeAlways;
            break;
        }
    }
like image 193
iPatel Avatar answered Nov 02 '22 09:11

iPatel


U can do it in Xib. I am attaching the screenshot.

enter image description here

And programmatically

myUITextField.clearButtonMode = UITextFieldViewModeAlways;
like image 36
Sahil Mahajan Avatar answered Nov 02 '22 09:11

Sahil Mahajan


This is the default behavior of the search bar. Because if the UITextField is blank then there is no need to press it.

like image 33
user2526811 Avatar answered Nov 02 '22 09:11

user2526811