搜索条_UISearchBar

注意:要继承UISearchResultsUpdating,实现更新搜索结果的方法:updateSearchResultsForSearchController:(UISearchController *)searchController

//
//  JJTableViewController.m
//  搜索条_UISearchBar
//
//  Created by 一介布衣 on 16/3/20.
//  Copyright © 2016年 HUAMANLOU. All rights reserved.
//

#import "JJTableViewController.h"
#import "JJResultTableViewController.h"

@interface JJTableViewController ()

@property (nonatomic,strong) NSMutableArray *mutLists;
@property (nonatomic,strong) UISearchController *searchController;
@property (nonatomic,strong) JJResultTableViewController *resultTableViewVc;

@end

NSString *cellId = @"cellId";

@implementation JJTableViewController

#pragma mark - 懒加载
- (NSMutableArray *)mutLists {
    if (_mutLists == nil) {
        _mutLists = [NSMutableArray array];
    }
    return _mutLists;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 制造假数据
    for (int i=0; i<100; i++) {
        [self.mutLists addObject:[NSString stringWithFormat:@"%02d-data%02d",i,i]];
    }
    
    // 初始化搜索条
    self.resultTableViewVc = [[JJResultTableViewController alloc] init];
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultTableViewVc];
    self.tableView.tableHeaderView = self.searchController.searchBar;
    
    self.searchController.searchResultsUpdater = self;
    
}



#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.mutLists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    cell.textLabel.text = self.mutLists[indexPath.row];
    
    return cell;
}


#pragma mark - 更新搜索结果
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
   
    // 谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",self.searchController.searchBar.text];
    
    NSArray *arr = [NSArray arrayWithArray:[self.mutLists filteredArrayUsingPredicate:predicate]];
    
    self.resultTableViewVc.arrayList = arr;
    
    [self.resultTableViewVc.tableView reloadData];
}


@end

你可能感兴趣的:(搜索条_UISearchBar)