nja
nja

Reputation: 571

How can I programmatically force a search in the UISearchBar?

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?

Upvotes: 26

Views: 21193

Answers (9)

Robin Stewart
Robin Stewart

Reputation: 3903

Swift 5

If you just have a UISearchBar (not a UISearchViewController):

let searchBar: UISearchBar
searchBar.text = "foo" // Reset the search text
searchBar.becomeFirstResponder() // Select the field and bring up the keyboard

Upvotes: 0

hstdt
hstdt

Reputation: 6243

let searchBar: UISearchBar = /* The Searchbar */
searchBar.delegate?.searchBar?(searchBar, textDidChange: "")
searchBar.text = ""

Upvotes: 2

nanospeck
nanospeck

Reputation: 3548

This worked - Swift 4

   searchBar.text="Amber"
   self.searchBar(self.searchBar, textDidChange: "Amber")

Upvotes: -1

Robban
Robban

Reputation: 1221

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"

Upvotes: 24

Oluwatobi Omotayo
Oluwatobi Omotayo

Reputation: 1879

After making sure that the text you want is inside your search bar you can call self.searchBarSearchButtonClicked(searchBar) (passing in your search bar) assuming you have already implemented this UISearchBarDelegate method searchBarSearchButtonClicked(_ searchBar: UISearchBar)

Upvotes: 3

Saravanan B
Saravanan B

Reputation: 59

You can force your searchBar,

Objective C:

[self searchBar:yourSearchBarName textDidChange: yourSearchingString];

Swift 3.0:

self.searchBar(self.yourSearchBarName, textDidChange: yourSearchingString)

This will trigger your searchBar.

Upvotes: 4

JeanChRocha
JeanChRocha

Reputation: 87

seems dumb, but works, so it's not dumb ;)

NSString * forceReload = self.searchDisplayController.searchBar.text;
self.searchDisplayController.searchBar.text = forceReload;

Upvotes: 0

tiguero
tiguero

Reputation: 11537

Yes you only need to make an implicit call to the searchBarSearchButtonClicked: on your UISearchbarDelegate. Have a look to the official doc for more info about this delegate.

Upvotes: 1

Pascal
Pascal

Reputation: 16941

Just have the search input field become the first responder:

[self.searchInputField becomeFirstResponder];

Upvotes: 6

Related Questions