搜索条(在表格中)实现搜索功能

/*
此代码可通过首字母实现搜索
*/
<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];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值