#import "ViewController.h"
@interface ViewController ()<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];
} @end