简体   繁体   English

如何以编程方式关闭 UISearchBar?

[英]How to programmatically dismiss a UISearchBar?

I have a standard table view, with a UISearchController implemented via a NIB.我有一个标准的表视图,带有通过 NIB 实现的 UISearchController。 I want to mimic what happens when the user clicks "Cancel" in the search bar - the normal behaviour is that the search bar goes away and the table returns to its original state.我想模拟当用户在搜索栏中单击“取消”时会发生什么 - 正常行为是搜索栏消失并且表格返回其原始状态。 Basically, I want to have the same happen when the user selects an item that appears in their search results.基本上,当用户选择出现在其搜索结果中的项目时,我希望发生同样的情况。

I can't find anywhere the process of what happens when the user clicks "Cancel".我在任何地方都找不到用户单击“取消”时发生的过程。

This is a sorta old question, but I just beat my head against this for an hour or two and finally figured it out, so I thought I'd share for posterity.这是一个有点老的问题,但我只是在这个问题上挣扎了一两个小时,终于弄明白了,所以我想我会分享给后代。 At first I tried doing things like resigning first responder / deleting search text / etc by hand, but in this view I wanted the user to be able to possibly use the search bar multiple times, and doing things manually was meaning that the search bar would have had to be re-set-up every time the user started editing it again - seemed like the wrong approach.起初,我尝试手动执行诸如辞退第一响应者/删除搜索文本等操作,但在此视图中,我希望用户能够多次使用搜索栏,而手动操作意味着搜索栏将每次用户再次开始编辑时都必须重新设置 - 似乎是错误的方法。 Here's what I did:这是我所做的:

I had already added the search bar, with the optional search display controller, in Interface Builder.我已经在 Interface Builder 中添加了带有可选搜索显示控制器的搜索栏。 In my implementation, I set up a UISearchDisplayController IBOutlet, and then linked it to the search display controller using IB.在我的实现中,我设置了一个 UISearchDisplayController IBOutlet,然后使用 IB 将其链接到搜索显示控制器。 Finally, in the spot where I want to dismiss the search bar, I simply have to call:最后,在我想关闭搜索栏的地方,我只需要调用:

[mySearchController setActive:NO];

Works like a charm!像魅力一样工作!

Usually, the searchBarCancelButtonClicked: method looks something like this:通常, searchBarCancelButtonClicked: 方法看起来像这样:

yourSearchBar.text = @"";
[yourTableView reloadData];
[yourSearchBar resignFirstResponder];

Here is how i solved this problem after a few hours of experiments =)这是我在几个小时的实验后解决这个问题的方法 =)

for(UIView *subView in self.searchDisplayController.searchBar.subviews){
    if([subView isKindOfClass:UIButton.class])
    {
        UIButton *cancelButton = (UIButton*)subView;
        [cancelButton sendActionsForControlEvents: UIControlEventTouchUpInside];
        break;
    } 
}

Set active also cleared my UISearchBar text and so my array of data items would get cleared, therefore this worked for me: Set active 也清除了我的UISearchBar文本,因此我的数据项数组将被清除,因此这对我有用:

self.searchController.dismissViewControllerAnimated(true, completion: nil)

This cleared the UIDimmingView and left my search text alone - perfect in my case.这清除了UIDimmingView并留下了我的搜索文本 - 对我来说是完美的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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