简体   繁体   中英

How to trigger cancel button in UISearchBar?

How to trigger programmatically cancel button in UISearchBar, like if you have tapped cancel button?

I have a UISearchBar in the top of a UITableView and after a search, when someone select a row, I want to trigger programmatically cancel button in the UISearchBar?

EDIT: Without user interaction.

For a view controller using a search display controller, you can set

self.searchDisplayController.active = NO;
// or:
[self.searchDisplayController setActive:NO animated:YES];

to dismiss the search interface.

You need to implement the UISearchBarDelegate . Once you've done that, use:

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar

Tells the delegate that the cancel button was tapped.

Then use:

[self searchBarCancelButtonClicked:yourSearchBar];

For the new UISearchController (introduced in 2014 with iOS 8) you can call:

[self.searchController setActive:FALSE];

or

self.searchController.active = FALSE;

(No flag for animation, I've found it always animates.)

对于iOS 8,使用UISearchController ,以编程方式实现取消按钮动作,使用:

[self.searchController setActive:NO]; 

对于 Swift 4.2 版本,您可以编写如下代码:

searchController?.isActive = false
self.navigationItem.searchController?.isActive = false // above iOS 8.0
// or:    
self.searchDisplayController.active = NO; // was deprecated in iOS 8.0
// or:
[self.searchDisplayController setActive:NO animated:YES]; // Obejective-C

These are some of the variants that accomplish the mentioned task

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM