How can I programmatically force a search in the UISearchBar?

nja picture nja · Sep 16, 2012 · Viewed 18.5k times · Source

How can I force the UISearchBar to automatically start a new search (like pressing the Search button)? Is there an easy way to achieve this?

Answer

Robban picture Robban · Jun 17, 2014

I found that I needed to set the UISearchViewController to active before changing the value of the search field programatically to make UISearchViewController automatically perform the search:

// Need to set the searchDisplayController to active to 
// make the changes in search text trigger a search.
self.searchDisplayController.active = YES;
self.searchDisplayController.searchBar.text = @"New search string";

Swift 4

self.searchController.isActive = true
self.searchController.searchBar.text = "New search string"