搜索控件

ViewController.m
#import “ViewController.h”

@interface ViewController ()

<UITableViewDataSource,UITableViewDelegate>
{
    
    NSArray *allArr;   // 全数据数组
    NSArray *filterArr; // 过滤后的数组
    UITableView *tbv;  // 表格
    UISearchDisplayController *seDC; // 搜索控制器
}

@end

@implementation ViewController

接下来是viewDidLoad

  • (void)viewDidLoad {
    [super viewDidLoad];
// 6.数据源数组
    allArr = @[@"abcddde",@"abcd",@"a",@"bcde",@"aabc",@"ebd",@"abcdefg"];
    
    
    
    // 表格
    // 1.frame
    tbv = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    // 2.设置数据源和代理
    tbv.dataSource = self;
    tbv.delegate = self;
    // 3.把表格添加到主视图
    [self.view addSubview:tbv];
    
    
    // 搜索条
    UISearchBar *seBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    seBar.placeholder = @"请输入想搜索的内容!!";
    // 将搜索条设置成表格的组头视图
    tbv.tableHeaderView = seBar;
    
    // 初始化搜索控制器
    seDC = [[UISearchDisplayController alloc]initWithSearchBar:seBar contentsController:self];
    // 设置新的控制器的代理 和数据源
    seDC.searchResultsDelegate = self;
    seDC.searchResultsDataSource = self; 

    
    
}

// 实现协议中的方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if(tableView == tbv){
        
        return allArr.count;
    }else{
        
        // 谓词 ->过滤
        // 创建谓词 - >根据我们搜索的内容的变化而变化
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"self contains [cd] %@",seDC.searchBar.text];
        // 通过谓词去过滤  数组(allArr)
        filterArr = [NSArray arrayWithArray:[allArr filteredArrayUsingPredicate:pred]];
        return filterArr.count;
        
        
    }
    
    
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *reuse = @"cell";
    // 先用旧的
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    // 再用新的
    if(!cell){
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
    }
    
    if(tableView == tbv){
    // 展示数据.
        cell.textLabel.text = allArr[indexPath.row];
    }else{
        // 过滤之后的世界了.
        cell.textLabel.text = filterArr[indexPath.row];
    }
    
    return cell;
    
}

// 隐藏状态栏
-(BOOL)prefersStatusBarHidden{
    
    return YES;
}

@end
效果运行图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值