How to trigger cancel button in UISearchBar?

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

[self.searchController setActive:NO]; 

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.


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

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