viewController.m
#import "ViewController.h"
#import "TableViewCell.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating>
{
UITableView *table;
UISearchController *sear;
NSMutableArray *arr;
NSArray *arr2;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建表格
table=[[UITableView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height -20)];
[table registerClass:[TableViewCell class] forCellReuseIdentifier:@"Mycell"];
//设置代理
table.dataSource=self;
table.delegate=self;
//添加到视图
[self.view addSubview:table];
//创建搜索条
sear=[[UISearchController alloc]initWithSearchResultsController:nil];
sear.searchBar.placeholder=@"搜索";
sear.searchResultsUpdater=self;
table.tableHeaderView=sear.searchBar;
//创建数据
arr=[NSMutableArray arrayWithObjects:@"one",@"two",@"three", nil];
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSPredicate *pre=[NSPredicate predicateWithFormat:@"self contains %@",sear.searchBar.text];
arr2=[arr filteredArrayUsingPredicate:pre];
[table reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(sear.isActive==YES)
{
return arr2.count;
}
return arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Mycell" forIndexPath:indexPath];
if(sear.isActive==YES)
{
cell.textLabel.text=arr2[indexPath.row];
}
else
{
cell.textLabel.text=arr[indexPath.row];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 50;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}