@interface ViewController ()<</span>UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating >
@property (nonatomic,strong) UISearchController *searchController;
//StoryBoard創建的tableView
@property (strong, nonatomic) IBOutlet UITableView *tableView;
//數據源數組
@property (nonatomic,strong) NSMutableArray *dataList;
//搜索到數據數組
@property (nonatomic,strong) NSMutableArray *searchList;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createSearchBar];
[self createData];
}
- (void)createSearchBar{
self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
//設置顯示搜索的控制器
self.searchController.searchResultsUpdater = self;
// 設置開始搜索時背景顯示與否(default is YES)
self.searchController.dimsBackgroundDuringPresentation = NO;
//展示時是否隱藏naviBar (default is YES)
self.searchController.hidesNavigationBarDuringPresentation = NO;
}
- (void)createData{
//將搜索欄設置爲tableView的頭部視圖
self.tableView.tableHeaderView = self.searchController.searchBar;
//tableView代理
self.tableView.delegate = self;
self.tableView.dataSource = self;
//初始化數據源數組
self.dataList = [NSMutableArray arrayWithCapacity:0];
for (NSInteger i = 0; i < 100; i++) {
[self.dataList addObject:[NSString stringWithFormat:@"騷軍 %ld號",i]];
}
}
//tableView @required
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (self.searchController.active) {
return self.searchList.count;
}
return self.dataList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
}
if (self.searchController.active) {
[cell.textLabel setText:self.searchList[indexPath.row]];
}else{
[cell.textLabel setText:self.dataList[indexPath.row]];
}
return cell;
}
//updataSearchTesultsForSearchController 進行過濾
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
//獲取searchBar搜索的內容
NSString *searchString = self.searchController.searchBar.text;
//謂詞
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
//判斷搜索數組是否爲空
if (self.searchList != nil) {
[self.searchList removeAllObjects];
}
//使用謂詞過濾數據
self.searchList = [NSMutableArray arrayWithArray:[_dataList filteredArrayUsingPredicate:predicate]];
//刷新
[self.tableView reloadData];