首页 > 代码库 > 点击搜索取消UISearchDisplayController的搜索状态

点击搜索取消UISearchDisplayController的搜索状态

         一般,我们用到UISearchDisplayController的时候,都是须要对一个数据源进行刷选,在UISearchDisplayController自带的tableView中展示出来,然后点击退出详情.我近期在做大众点评第三方的时候,遇到一个问题,我展示出了所有商店,想加搜索功能,可是不知道输入的搜索keyword去跟什么匹配,大众点评也并没有提供一个用来刷选的数据源接口,这样,我仅仅能自己输入keyword,不用它数据源提供刷选补全内容,而直接点击弹出键盘的搜索键,进行搜索.只是点击搜索后,UISearchDisplayController的搜索状态并不会取消,这并非我想要了效果,调试了非常久,终于还是攻克了.

#pragma mark - 点击搜索,能够取消搜索状态
#pragma mark UISearchDisplayDelegate
- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller
{
    for (UIView *view in controller.searchBar.subviews)
    {
         NSLog(@"%d__|---%@",__LINE__,view);
        for (UIView *subView in view.subviews)
        {
             NSLog(@"%d__|!!!%@",__LINE__,subView);
            //  获取"取消"button
            if([subView isKindOfClass:[UIButton class]])
            {
                UIButton *cancelButton = (UIButton *)subView;
                //  获取点击"取消"button的响应事件(actionsForTarget 这种方法返回的是一个数组)
                self.cancelSearchSELString = [[cancelButton actionsForTarget:controller.searchBar forControlEvent:UIControlEventTouchUpInside] objectAtIndex:0];
                //  响应通知,运行方法直接用上面获得的响应事件方法,转换一下(这是个知识点,能够扩展下)
                [[NSNotificationCenter defaultCenter] addObserver:controller.searchBar selector:NSSelectorFromString(self.cancelSearchSELString) name:@"cancelSearch" object:nil];
            }
        }
    }
}

#pragma mark UISearchBarDelegate------点击搜索button
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{

    //  获取你想搜索的终于完整keyword(一般能够用来做搜索历史展示)  
    NSLog(@"%s__%d__|%@",__FUNCTION__,__LINE__,searchBar.text);
    //  点击button时,公布取消搜索状态通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"cancelSearch" object:nil];
    //  公布---响应---取消通知
    [[NSNotificationCenter defaultCenter] removeObserver:searchBar name:@"cancelSearch" object:nil];
}


@扩展一下知识点:

能够用actionsForTarget方法,来获取针对某一特定事件目标的所有动作列表:
[java] view plaincopyprint?
NSArray* myActions = [ myControl actionForTarget:UIControlEventValueChanged ];  

//  一些特别的转换
@class NSString, Protocol;

FOUNDATION_EXPORT NSString *NSStringFromSelector(SEL aSelector);
FOUNDATION_EXPORT SEL NSSelectorFromString(NSString *aSelectorName);

FOUNDATION_EXPORT NSString *NSStringFromClass(Class aClass);
FOUNDATION_EXPORT Class NSClassFromString(NSString *aClassName);

FOUNDATION_EXPORT NSString *NSStringFromProtocol(Protocol *proto) NS_AVAILABLE(10_5, 2_0);
FOUNDATION_EXPORT Protocol *NSProtocolFromString(NSString *namestr) NS_AVAILABLE(10_5, 2_0);



点击搜索取消UISearchDisplayController的搜索状态