Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 265
nja Avatar asked Sep 16 '12 14:09

nja


6 Answers

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"
like image 140
Robban Avatar answered Nov 18 '22 04:11

Robban


Just have the search input field become the first responder:

[self.searchInputField becomeFirstResponder];
like image 42
Pascal Avatar answered Nov 18 '22 05:11

Pascal


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.

like image 25
Saravanan B Avatar answered Nov 18 '22 03:11

Saravanan B


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)

like image 21
Oluwatobi Omotayo Avatar answered Nov 18 '22 04:11

Oluwatobi Omotayo


let searchBar: UISearchBar = /* The Searchbar */
searchBar.delegate?.searchBar?(searchBar, textDidChange: "")
searchBar.text = ""
like image 2
hstdt Avatar answered Nov 18 '22 05:11

hstdt


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.

like image 1
tiguero Avatar answered Nov 18 '22 03:11

tiguero