使用UISearchController需要注意的事项

开发中为ViewController头部添加搜索框的时候,用到了UISearchController,笔者使用时,遇到了一些坑,在此记下来,共勉

1.该ViewController要继承自UITableViewController

2.cell要根据searchController.active的值判断来加载相应数据

3.核心代码如下

UISearchController *searchController = [[UISearchController alloc]  initWithSearchResultsController:nil];

searchController.searchResultsUpdater = self;

// searchController.dimsBackgroundDuringPresentation = YES;//搜索时tableView添加蒙版

// searchController.hidesNavigationBarDuringPresentation = NO;//搜索时是否需要隐藏导航栏  默认为YES

searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x,self.searchController.searchBar.frame.origin.y,self.searchController.searchBar.frame.size.width,44.0);

self.searchController = searchController;

self.tableView.tableHeaderView = self.searchController.searchBar;

self.definesPresentationContext=YES;

4.实现代理方法<UISearchResultsUpdating>设置数据来源

#pragma mark - UISearchResultsUpdating

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    NSString *searchString = [self.searchController.searchBar  text];

    NSPredicate  *preicate = [NSPredicate  predicateWithFormat:@"SELF CONTAINS[c]  %@",    searchString];

     if(self.searchList != nil) {

          [self.searchList  removeAllObjects];

      }

     //过滤数据

      self.searchList = [NSMutableArray  arrayWithArray:[self.dataArray  filteredArrayUsingPredicate:preicate]];

      //刷新表格

       [self.tableView  reloadData];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容