搜索框

直接上代码
VIewController.m

<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *tbv;    // 表格
    
    NSArray *data;      // 所有数据
    NSArray *filterData;// 过滤数据
    
    UISearchDisplayController *searchDC;    // 搜索控制器
}

viewDidLoad

// 创建所有数据
    data = [NSArray arrayWithObjects:@"ABCD",@"A",@"ABC",@"NDC",nil];
    // 创建表格
    tbv = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    
    // 设置代理
    tbv.delegate = self;
    tbv.dataSource = self;
    
    // 将表格添加到视图上
    [self.view addSubview:tbv];
    
    
    // 创建搜索条
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    
    // 设置提示文字
    searchBar.placeholder = @"搜索";
    searchBar.showsCancelButton = YES;
    
    // 将 searchBar 添加到表格的页眉上
    tbv.tableHeaderView = searchBar;
    
    // 把搜索控制器  和当前控制器关联起来
    searchDC = [[UISearchDisplayController alloc]initWithSearchBar:searchBar contentsController:self];
    
    // 设置代理
    searchDC.searchResultsDelegate = self;
    searchDC.searchResultsDataSource = self;
    
    
    
}

// ===== 数据源方法 =====

// 设置组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //    return data.count;
    
    // 判断当前是哪个 tableView
    if (tableView == tbv)
    {
        // 返回所有数据个数
        return data.count;
    }
    else
    {
        // 使用谓词进行过滤
        // 创建谓词
        // contains [cd] : 是否包含 XXX , 并忽略大小写,忽略重音字母
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"self contains [cd] %@",searchDC.searchBar.text];
        
        // 执行过滤
        filterData = [NSArray arrayWithArray:[data filteredArrayUsingPredicate:pred]];
        
        // 返回过滤数组个数
        return filterData.count;
        
    }
    
}

// 设置 cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 设置可重用标识符
    static NSString *reuseID = @"cell";
    
    // 根据可重用标识符查找cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
    
    // 如果没有找到 创建cell
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID];
    }
    //
    //    // 设置cell内容
    //    cell.textLabel.text = data[indexPath.row];
    
    // 判断如果是是原来的tableView 返回所有数据 否则则返回过滤数据
    if (tableView == tbv)
    {
        cell.textLabel.text = data[indexPath.row];
    }
    else
    {
        cell.textLabel.text = filterData[indexPath.row];
    }
    
    // 返回 cell
    return cell;
}


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

搜索框