美文网首页iOS资料iOS 开发 iOS开发技术分享
使用UISearchController需要注意的事项

使用UISearchController需要注意的事项

作者: 小码农_gjw | 来源:发表于2016-06-16 19:04 被阅读1654次

开发中为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];

}

相关文章

网友评论

    本文标题:使用UISearchController需要注意的事项

    本文链接:https://www.haomeiwen.com/subject/lygmdttx.html