Dismissing UISearchBar

2019-08-06 01:32发布

问题:

I have code that runs in searchBarCancelButtonClicked: I want to run the same code when the user clicks away from the searchbar, even though cancel isn't necessarily clicked. My current code is below but has an issue that I can't figure out. I have placed a UIView underneath the search bar that when clicked runs a method that does what I want.

The issue is that when the searchbar is active, the semi-transparent view associated with uisearchbar comes up on top of my view and clicking the view still just dismisses the searchbar, but doesn't run my method. After the searchbar is dismissed, clicking the view does run my method so I know that is ok. Basically I need to be able to make the view gesture active while the searchbar is the first responder.

- (BOOL)searchBarShouldBeginEditing:(UISearchBar*)searchBar {
    UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissSearch:)];
    UIView *transparentView = [[UIView alloc]initWithFrame:transparentViewRect];
    [transparentView setBackgroundColor:[UIColor blackColor]];
    [transparentView addGestureRecognizer:singleTap];
    [self.view addSubview:transparentView];
    [self.view bringSubviewToFront:transparentView];

    return  YES;

}

- (void) dismissSearch:(UITapGestureRecognizer *)tapGesture
{
  //Run my code
}

回答1:

I guess you can probably use the searchBarShouldEndEditing: or searchBarTextDidEndEditing: delegate methods...



回答2:

To solve mentioned issue (when tap on cell at UITablewView with search result), use this condition on searchBarShouldEndEditing: or searchBarTextDidEndEditing: methods:

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
  if (self.searchDisplayController.searchResultsTableView.hidden) {
        self.searchBar.hidden = true;
  }

  return true;
}