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

banu picture banu · Aug 13, 2013 · Viewed 9.1k times · Source

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.

Answer

iPatel picture iPatel · Aug 13, 2013
UITextField *searchBarTextField = nil;
    for (UIView *subview in self.searchBar.subviews)
    {
        if ([subview isKindOfClass:[UITextField class]])
        {
            searchBarTextField = (UITextField *)subview;
            searchBarTextField.clearButtonMode = UITextFieldViewModeAlways;
            break;
        }
    }