JiteshW
JiteshW

Reputation: 2205

UISearchBar cancel button not responding

I have implemented searchbar which shows cancel button once user has focus in searchbar. For this I have written searchBar.showsCancelButton = YES; in my searchBarTextDidBeginEditing method. In searchBarSearchButtonClicked, I resign the keyboard so that user can view full tableview.

Problem: At this point the searchbar cancel button is not responding. It only responds once searchbar gets focus again. Is this the default property of search bars cancel button or am I missing something in my code. I want to use cancel button without giving the focus in searchbar again.

Upvotes: 8

Views: 2831

Answers (4)

gerbil
gerbil

Reputation: 913

The above method stopped working, this is tested and working on iOS 17.0:

- (void)enableCancelOnSearchBar
{
    [self enableButtonsForView:self.searchBar];
}

- (void)enableButtonsForView:(UIView*)view {
    NSArray<UIView*>* subviews = [view subviews];
    [subviews fbl_forEach:^(UIView * _Nonnull value) {
        if ([value isKindOfClass:[UIButton class]]) {
            [(UIButton*)value setEnabled:YES];
        } else {
            [self enableButtonsForView:value];
        }
    }];
}

fbl_forEach curtesy of FBLFunctional[https://github.com/google/functional-objc] .

Upvotes: 0

Baby Groot
Baby Groot

Reputation: 4279

This is search bar cancel button's default behaviour. If you want other functionality, you can just uncheck cancelbutton property for search bar and can use UIButton as cancel button.

Upvotes: 4

Rajneesh071
Rajneesh071

Reputation: 31081

Yes you can make your UISearchBar cancel button responding. By default it is disable but your can access it's sub view and then set enable to cancel button.

for (id object in [mySearchBar subviews])
{
    if ([object isKindOfClass:[UIButton class]])
    {
        UIButton *searchBarCancelBtn = (UIButton*)object;
        [searchBarCancelBtn setEnabled:YES];
    }
}

Follow this answer if you want some other logic Custom clear button in UISearchBar text field

Upvotes: 4

iNeal
iNeal

Reputation: 1729

I think its a default behavior of UISearchBar when it gets focus then and only then the cancel button will be enabled. You cannot get cancel button event of UISearchBar when it has no focus.

So My suggession to achieve your task is,

  • Create a ToolBar
  • Insert UIBarButtonItem with custom view as UISearchBar
  • Insert UIBarButtonItem named "Cancel" with action

Upvotes: 3

Related Questions