/*
此代码可通过首字母实现搜索
*/
<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>{
NSArray *_allData;
//搜索条
UISearchBar *search;
//搜索控制器
UISearchDisplayController *displayCon;
//搜索结果
NSArray *_resultArr;
}
@property(nonatomic,strong)UITableView *table;//表格
//重写get方法
-(UITableView *)table{
if (!_table) {
_table = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20) style:UITableViewStylePlain];
_table.dataSource = self;
_table.delegate = self;
}
return _table;
}
- (void)viewDidLoad {
[super viewDidLoad];
//模拟数据
// _allData = [NSArray arrayWithArray:[UIFont familyNames]];
_allData = [NSArray arrayWithObjects:@"小明",@"李花",@"周华",@"丁俊晖",@"王强", nil];
[self.view addSubview:self.table];
//初始化搜索条
search = [[UISearchBar alloc]init];
//设置提示文字
search.placeholder = @"搜索姓名";
search.delegate = self;
//初始化搜索控制器
displayCon = [[UISearchDisplayController alloc]initWithSearchBar:search contentsController:self];
//设置代理
displayCon.searchResultsDataSource =self;
displayCon.searchResultsDelegate =self;
//设置头视图
self.table.tableHeaderView = search;
// _resultArr = [[NSMutableArray alloc]init];
}
//返回多少行数据
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (self.table == tableView) {
return _allData.count;
}else{
return _resultArr.count;
}
}
//cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellId = @"cellid";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
}
if (self.table == tableView) {
cell.textLabel.text = _allData[indexPath.row];
}else{
cell.textLabel.text = [_resultArr objectAtIndex:indexPath.row];
}
return cell;
}
//搜索条
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
NSMutableArray *tmp = [NSMutableArray array];
//筛选数据 把输入的字母全部转换为大写(让判断不区分大小写)
NSString *str = [search.text uppercaseString];
//遍历人名数组
for (NSString *s in _allData) {
//判断是否以输入的字母开头
if([[s uppercaseString] hasPrefix:str] ){
[tmp addObject:s];
}
}
_resultArr = [NSArray arrayWithArray:tmp];
[self.table reloadData];
}
搜索条(在表格中)实现搜索功能
最新推荐文章于 2019-08-13 17:10:12 发布