1.searchResultsUpdater:設置顯示搜索結果的控制器ide
_mySearchController.searchResultsUpdater = self;
2.dimsBackgroundDuringPresentation:設置開始搜索時背景顯示與否atom
_mySearchController.dimsBackgroundDuringPresentation = NO;
3.[searchBar sizeToFit]:設置searchBar位置自適應代理
[_mySearchController.searchBar sizeToFit];
4.設置searchBar爲UITableView的頭部視圖code
self.myTableView.tableHeaderView = self.mySearchController.searchBar;
5.UISearchResultsUpdating:代理方法orm
話很少說,直接上代碼string
@interface ViewController () @property (nonatomic, strong) UITableView *myTableView; @property (nonatomic, strong) NSMutableArray *visableArray; @property (nonatomic, strong) NSMutableArray *filterArray; @property (nonatomic, strong) NSMutableArray *dataSourceArray; @property (nonatomic, strong) UISearchController *mySearchController; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self initial]; } - (void)initial{ self.dataSourceArray = [NSMutableArray array]; self.filterArray = [NSMutableArray array]; for (int i = 0; i < 26; i++) { for (int j = 0; j < 4; j++) { NSString *str = [NSString stringWithFormat:@"%c%d", 'A'+i, j]; [self.dataSourceArray addObject:str]; } } self.visableArray = self.dataSourceArray; self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; _myTableView.delegate = self; _myTableView.dataSource = self; [self.view addSubview:_myTableView]; self.mySearchController = [[UISearchController alloc] initWithSearchResultsController:nil]; _mySearchController.searchResultsUpdater = self; _mySearchController.dimsBackgroundDuringPresentation = NO; [_mySearchController.searchBar sizeToFit]; self.myTableView.tableHeaderView = self.mySearchController.searchBar; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ if (!_visableArray || _visableArray.count == 0) { _visableArray = _dataSourceArray; } return _visableArray.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"identifier"]; } cell.textLabel.text = [_visableArray objectAtIndex:indexPath.row]; return cell; } - (void)updateSearchResultsForSearchController:(UISearchController *)searchController{ NSString *filterString = searchController.searchBar.text; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [c] %@", filterString]; self.visableArray = [NSMutableArray arrayWithArray:[self.dataSourceArray filteredArrayUsingPredicate:predicate]]; [self.myTableView reloadData]; }