当做搜索时常常希望能在输入的时候出现搜索关键字,如下效果
实现起来也很简单,只要在searchbar 文本改变的时候从数据源中过滤所包含的谓词数据即可,所包好的谓词数据生成另外一个数据集合,然后根据状态reload表格就好了,这里我使用xib去生成一个UISearchbar,然后给tabbleview添加头文件.
1 // 2 // ViewController.m 3 // 搜索条-uisearchbar 4 // 5 // Created by taofuxn on 16/11/8. 6 // Copyright © 2016年 taofuxn. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 11 @interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate> 12 13 @property (weak, nonatomic) IBOutlet UITableView *table; 14 @property (weak, nonatomic) UISearchBar *searchbar; 15 16 17 @end 18 19 @implementation ViewController 20 21 22 NSMutableArray *tableData; 23 NSMutableArray *searchData; 24 bool isSearch; 25 26 - (void)viewDidLoad { 27 [super viewDidLoad]; 28 29 tableData = [[NSMutableArray alloc]init]; 30 searchData = [[NSMutableArray alloc]initWithObjects:@"搜索历史", nil]; 31 for (int i = 0; i < 30; i++) { 32 [tableData addObject:[NSString stringWithFormat:@"德玛西亚之%d",i]]; 33 } 34 isSearch = NO; 35 36 //从xib中加载view 37 NSArray *viewrray= [[NSBundle mainBundle]loadNibNamed:@"searchview" owner:nil options:nil]; 38 UIView *xb=[viewrray firstObject]; 39 40 self.searchbar = (UISearchBar*) xb; 41 self.table.tableHeaderView = self.searchbar; 42 43 self.table.dataSource = self; 44 self.table.delegate = self; 45 46 self.searchbar.delegate = self; 47 48 } 49 50 51 52 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 53 { 54 if (isSearch) { 55 return searchData.count; 56 }else{ 57 return tableData.count; 58 } 59 } 60 61 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 62 { 63 static NSString *tag = @"taofuxn"; 64 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tag]; 65 if (cell ==nil) { 66 cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tag]; 67 } 68 69 70 NSInteger row = indexPath.row; 71 72 if (isSearch) { 73 cell.textLabel.text = [searchData objectAtIndex:row]; 74 }else{ 75 cell.textLabel.text =[tableData objectAtIndex:row]; 76 } 77 78 return cell; 79 80 } 81 //搜索框按取消键时 82 -(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar 83 { 84 isSearch = NO; 85 [self.table reloadData]; 86 } 87 88 //搜索框中文本改变 89 -(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText 90 { 91 92 //执行搜索 93 [self filterBySubstring:searchText]; 94 95 } 96 //点击开始搜索 97 -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar 98 { 99 [self filterBySubstring:searchBar.text]; 100 101 //放弃做键盘第一响应者 102 [searchBar resignFirstResponder]; 103 } 104 105 -(void) filterBySubstring:(NSString *)text 106 { 107 108 isSearch = YES; 109 //通过定义搜索谓词来过滤数组数据 110 NSPredicate* cate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",text]; 111 112 searchData = [tableData filteredArrayUsingPredicate:cate]; 113 114 [self.table reloadData]; 115 } 116 117 118 119 @end
其中xib如下:
ok,运行起来,一个简单的界面就完成了