How can I programmatically force a search in the U

2020-05-25 04:13发布

问题:

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?

回答1:

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"


回答2:

Just have the search input field become the first responder:

[self.searchInputField becomeFirstResponder];


回答3:

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.



回答4:

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)



回答5:

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.



回答6:

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

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


回答7:

I can not get the delegate object but the searchBar itself, this code can work.

let searchBar: UISearchBar = 
searchBar.delegate?.searchBar?(searchBar, textDidChange: "")
searchBar.text = ""


回答8:

This worked - Swift 4

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