iOS13 中UISearchController用法
背景
iOS8开始,苹果引入了新的UISearchController替代UISearchDisplayController。iOS13编译则报错:*** Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘UISearchDisplayController is no longer supported when linking against this version of iOS. Please migrate your application to UISearchController.’
直接上代码
一、需要遵守的协议在
<UITableViewDataSource,UITableViewDelegate,UISearchControllerDelegate,UISearchResultsUpdating>
二、具体代码
@property(nonatomic,strong)UISearchController *searchController;
_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
_searchController.searchResultsUpdater = self;
// 默认为YES,控制搜索控制器的灰色半透明效果
_searchController.dimsBackgroundDuringPresentation = NO;(若为YES则搜索的结果可能无法点击)
// 默认为YES,控制搜索时,是否隐藏导航栏
// _searchController.hidesNavigationBarDuringPresentation = NO;
_searchController.searchBar.delegate = self;
_searchController.searchBar.placeholder = @“搜索”;
[_searchController.searchBar sizeToFit];
self.definesPresentationContext = YES;
//设置搜索框
self.tableView.tableHeaderView = self.searchController.searchBar;
self.searchController.delegate = self;
代理方法
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSLog(@"搜索框");
NSString *searchString = [self.searchController.searchBar text];
NSLog(@"%@", searchString);
NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
if (self.searchResultArray!= nil) {
[self.qunArray removeAllObjects];
}
//过滤数据
self.searchResultArray= [NSMutableArray arrayWithArray:[_qunArray filteredArrayUsingPredicate:preicate]];
//刷新表格
[self.tableView reloadData];
}
// 当搜索控制亲已经消失时
- (void)didDismissSearchController:(UISearchController *)searchController{
NSLog(@"取消");
}
// 当搜索控制器即将消失时
- (void)willDismissSearchController:(UISearchController *)searchController{
NSLog(@"将要取消");
}
三、注意点
numberOfSectionsInTableView、numberOfRowsInSection、cellForRowAtIndexPath、didSelectRowAtIndexPath等方法需self.searchController.active 进行判断
插入链接与图片
链接: [link]https://me.csdn.net/bbs/qq_45039822