How can I programmatically force a search in the U

2020-05-25 03:59发布

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?

8条回答
Fickle 薄情
2楼-- · 2020-05-25 04:40

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.

查看更多
Luminary・发光体
3楼-- · 2020-05-25 04:43

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 = ""
查看更多
对你真心纯属浪费
4楼-- · 2020-05-25 04:46

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"
查看更多
闹够了就滚
5楼-- · 2020-05-25 04:55

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.

查看更多
Explosion°爆炸
6楼-- · 2020-05-25 05:01

Just have the search input field become the first responder:

[self.searchInputField becomeFirstResponder];
查看更多
疯言疯语
7楼-- · 2020-05-25 05:04

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

NSString * forceReload = self.searchDisplayController.searchBar.text;
self.searchDisplayController.searchBar.text = forceReload;
查看更多
登录 后发表回答