一看就懂demo下载地址:github
随着iOS9的发布,又有一些API被苹果禁止了,UISearchDisplayController就是其中一个,取而代之的是UISearchController,之前找了网上都没多少教程,上去stack overflow找了一下,又参考了一些官方文档,终于搞清了怎么用。
首先声明属性:
@property (strong, nonatomic) UISearchController *searchController;
然后设置:
self.searchController =
[[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = YES;
self.searchController.hidesNavigationBarDuringPresentation = YES;
self.searchController.searchBar.frame
= CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 40);
self.tableView.tableHeaderView = self.searchController.searchBar;
都是很直白的属性设置,其中searchresultupdater这个属性相当于delegate,设置当前对象负责更新数据。UISearchController只有一种初始化方法,如第一行代码所示,参数可以设置为nil。nil是表示直接在当前vc显示搜索后的内容,是最简单的一种使用方法。
实现UISearchResultsUpdating协议:
- (void)updateSearchResultsForSearchController:
(UISearchController *)searchController {
NSString *searchString = [self.searchController.searchBar text];
NSPredicate *predicate =
[NSPredicate predicateWithFormat:@"SELF CONTAINS[C] %@", searchString];
if (self.searchList) {
[self.searchList removeAllObjects];
}
self.searchList =
[NSMutableArray arrayWithArray:[self.dataList filteredArrayUsingPredicate:predicate]];
[self.tableView reloadData];
}