ViewController.m
#import “ViewController.h”
@interface ViewController ()
<UITableViewDataSource,UITableViewDelegate>
{
NSArray *allArr; // 全数据数组
NSArray *filterArr; // 过滤后的数组
UITableView *tbv; // 表格
UISearchDisplayController *seDC; // 搜索控制器
}
@end
@implementation ViewController
接下来是viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
// 6.数据源数组
allArr = @[@"abcddde",@"abcd",@"a",@"bcde",@"aabc",@"ebd",@"abcdefg"];
// 表格
// 1.frame
tbv = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
// 2.设置数据源和代理
tbv.dataSource = self;
tbv.delegate = self;
// 3.把表格添加到主视图
[self.view addSubview:tbv];
// 搜索条
UISearchBar *seBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
seBar.placeholder = @"请输入想搜索的内容!!";
// 将搜索条设置成表格的组头视图
tbv.tableHeaderView = seBar;
// 初始化搜索控制器
seDC = [[UISearchDisplayController alloc]initWithSearchBar:seBar contentsController:self];
// 设置新的控制器的代理 和数据源
seDC.searchResultsDelegate = self;
seDC.searchResultsDataSource = self;
}
// 实现协议中的方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(tableView == tbv){
return allArr.count;
}else{
// 谓词 ->过滤
// 创建谓词 - >根据我们搜索的内容的变化而变化
NSPredicate *pred = [NSPredicate predicateWithFormat:@"self contains [cd] %@",seDC.searchBar.text];
// 通过谓词去过滤 数组(allArr)
filterArr = [NSArray arrayWithArray:[allArr filteredArrayUsingPredicate:pred]];
return filterArr.count;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *reuse = @"cell";
// 先用旧的
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
// 再用新的
if(!cell){
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
}
if(tableView == tbv){
// 展示数据.
cell.textLabel.text = allArr[indexPath.row];
}else{
// 过滤之后的世界了.
cell.textLabel.text = filterArr[indexPath.row];
}
return cell;
}
// 隐藏状态栏
-(BOOL)prefersStatusBarHidden{
return YES;
}
@end
效果运行图: