48
votes

How to trigger programmatically cancel button in UISearchBar, like if you have tapped cancel button?

I have a UISearchBar in the top of a UITableView and after a search, when someone select a row, I want to trigger programmatically cancel button in the UISearchBar?

EDIT: Without user interaction.

6
Do you have a search display controller?Martin R

6 Answers

67
votes

For a view controller using a search display controller, you can set

self.searchDisplayController.active = NO;
// or:
[self.searchDisplayController setActive:NO animated:YES];

to dismiss the search interface.

29
votes

You need to implement the UISearchBarDelegate. Once you've done that, use:

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar

Tells the delegate that the cancel button was tapped.

Then use:

[self searchBarCancelButtonClicked:yourSearchBar];
29
votes

For the new UISearchController (introduced in 2014 with iOS 8) you can call:

[self.searchController setActive:FALSE];

or

self.searchController.active = FALSE;

(No flag for animation, I've found it always animates.)

5
votes

As for iOS 8, UISearchController is used, to achieve the cancel button action programmatically, Use:

[self.searchController setActive:NO]; 
3
votes

For Swift 4.2 version you can write as the following code:

searchController?.isActive = false
0
votes
self.navigationItem.searchController?.isActive = false // above iOS 8.0
// or:    
self.searchDisplayController.active = NO; // was deprecated in iOS 8.0
// or:
[self.searchDisplayController setActive:NO animated:YES]; // Obejective-C

These are some of the variants that accomplish the mentioned task