UISearchController的使用

时间:2022-11-04 11:43:51

- (void)addSearchController

{

_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];

_searchController.delegate = self;

_searchController.searchResultsUpdater = self;

// 必须要让searchBar自适应才会显示

[_searchController.searchBar sizeToFit];

_searchController.searchBar.delegate = self;

[_searchController.searchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];

_searchController.searchBar.backgroundImage = [UIImage imageWithColor:kAppBakgroundColor];

_searchController.searchBar.placeholder = @"用户ID/昵称";

_searchController.hidesNavigationBarDuringPresentation = NO;

_searchController.dimsBackgroundDuringPresentation = NO;

self.definesPresentationContext = NO;

//把searchBar 作为 tableView的头视图

self.tableView.tableHeaderView = _searchController.searchBar;

}

//把searchBar 作为 tableView的头视图

self.tableView.tableHeaderView = _searchController.searchBar;

#pragma mark - UISearchController的代理

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController

{

if (self.searchResults.count) {

[self.searchResults removeAllObjects];

}

NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"userId CONTAINS[c] %@",searchController.searchBar.text];

NSArray *array = [(NSArray *)self.searchArray filteredArrayUsingPredicate:searchPredicate];

self.searchResults = [NSMutableArray arrayWithArray:array];

//刷新表格

[self.tableView reloadData];

}

在tableView中使用时,可以根据_searchController.active的属性来判断是否显示搜索到的数据

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

if (_searchController.active) {

return [self.searchResults count];

}else{

id<IMAContactDrawerShowAble> drawer = [_contact objectAtIndex:section];

if ([self isDrawerFolded:drawer])

{

return 0;

}

else

{

return [drawer items].count;

}

}

}

参考地址:http://www.mamicode.com/info-detail-1156195.html

http://www.2cto.com/kf/201510/447287.html