51

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.

1
  • Do you have a search display controller? Commented Apr 11, 2013 at 20:39

6 Answers 6

69

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Aeew, thanks!! it works! I just don't know why I got down votes , thanks for your attention.
31

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.)

3 Comments

I tried the code above. It seems to be working in a demo I found, but doesn't seems to be working in my code, Do you have any idea? currently using self.searchDisplayController?.setActive(false, animated: true) to dismiss the Search Controller, but I fear because its a deprecated code.
@vinbhai4u hard to tell with your small comment. You should submit a new question where you explain things in more detail.
If you don't want animation, you can wrap it in a UIView.performWithoutAnimation block.
29

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]; 

2 Comments

No, I need to do it programmatically. without user interaction.
With Swift self.searchBarCancelButtonClicked(YourSearchBar)
6

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

[self.searchController setActive:NO]; 

1 Comment

Yes. This one does triggering search cancel search mode. In view disappear event, this call is critical to avoid memory leak when the view is in searching mode. Otherwise, the view would not be released from memory.
4

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

searchController?.isActive = false 

Comments

1
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.