- (void)viewDidLoad {
[super viewDidLoad];
//第一个数组为总库存,第二个数组用来存储搜索后的结果
_array=[NSMutableArray array];
_arrayb=[NSMutableArray array];
[_array addObject:@"1df"];
[_array addObject:@"2fbjdb"];
[_array addObject:@"3dbfjg"];
[_array addObject:@"nnnnn"];
[_array addObject:@"uuuuu"];
[self creatTableview];
}
//tableview展示搜索前和搜索后的结果
-(void)creatTableview{
_TableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
_TableView.dataSource=self;
_TableView.delegate=self;
[_TableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
[self.view addSubview:_TableView];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark tableview代理事件
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 70;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 60;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([_arrayb count]==0) {
return [_array count];
}else{
return [_arrayb count];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
if ([_arrayb count]==0) {
cell.textLabel.text=_array[indexPath.row];
}else{
cell.textLabel.text=_arrayb[indexPath.row];
}
return cell;
}
//头视图里放textfield用来做搜索框(非系统自带)
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view=[[UIView alloc]init];
_textF=[[UITextField alloc]init];
_textF.placeholder=@"搜索供应商";
_textF.delegate=self;
_textF.backgroundColor=[UIColor whiteColor];
[_textF addTarget : self action : @selector (didDone:) forControlEvents : UIControlEventEditingChanged ];
_textF.frame=CGRectMake(30, 10, self.view.bounds.size.width-60, 50);
[view addSubview:_textF];
return view;
}
//谓词过滤,实时搜索,刷新
-(void)didDone:(UITextField *)sender
{
[_arrayb removeAllObjects];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",_textF.text];
for (NSString *str in _array) {
if ([predicate evaluateWithObject:str]) {
if ([_arrayb containsObject:str]) {
}else{
[_arrayb addObject:str];
}
}
}
if ([_arrayb count]!=0) {
[_TableView reloadData];
}
if ([_textF.text isEqualToString:@""]) {
[_arrayb removeAllObjects];
[_TableView reloadData];
}
}