UISearchView

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating>
 4 {
 5     // 原始数据源
 6     NSMutableArray *_arrayM;
 7     // 搜素结果数据源
 8     NSMutableArray *_searchArrayM;
 9     
10     // 搜索控件
11     UISearchController *_searchC;
12     
13     UITableView *_tableView;
14 }
15 @end
16 
17 @implementation ViewController
18 
19 - (void)viewDidLoad {
20     [super viewDidLoad];
21     
22     // 1.获取原始数据
23     [self getData];
24     
25     // 2. 添加UI
26     [self addUI];
27 }
28 
29 - (void)getData
30 {
31     _arrayM = [NSMutableArray array];
32     _searchArrayM = [NSMutableArray array];
33     
34     for (int i = 'A'; i <= 'Z'; i ++) {
35         for (int j = 0; j < 10; j ++) {
36             [_arrayM addObject:[NSString stringWithFormat:@"%c--%d",i,j]];
37         }
38     }
39     
40     _searchArrayM = _arrayM;
41 }
42 
43 - (void)addUI
44 {
45     // 1. 添加tableview
46     _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
47     _tableView.delegate = self;
48     _tableView.dataSource = self;
49     [self.view addSubview:_tableView];
50     
51     // 2. 添加搜索控制器
52     _searchC = [[UISearchController alloc] initWithSearchResultsController:nil];
53     // 设置UISearchController 的代理
54     _searchC.searchResultsUpdater = self;
55     // 搜索蒙板是否显示(NO 不显示)
56     _searchC.dimsBackgroundDuringPresentation = NO;
57     // 设置UISearchController的位置
58     _tableView.tableHeaderView = _searchC.searchBar;
59     // 位置自适应
60     [_searchC.searchBar sizeToFit];
61 }
62 
63 - (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
64 {
65     
66     if (!_searchArrayM || _searchArrayM.count == 0) {// 如果没有搜索到内容,显示原始数据
67         _searchArrayM = _arrayM;
68     }
69     
70     return _searchArrayM.count;
71 }
72 
73 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
74 {
75     NSString *resuID = @"ID";
76     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:resuID];
77     if (cell == nil) {
78         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:resuID];
79     }
80     cell.textLabel.text = [_searchArrayM objectAtIndex:indexPath.row];
81     return cell;
82 }
83 
84 - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
85 {
86     // 1.获取搜索框中用户输入的关键字
87     NSString *filterStr = searchController.searchBar.text;
88     // 2.搜索包含关键字的内容
89     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains [c]%@",filterStr];
90     // 3.[_arrayM filteredArrayUsingPredicate:predicate] 从原始数据库中查找到包含关键字的数据
91     _searchArrayM = [NSMutableArray arrayWithArray:[_arrayM filteredArrayUsingPredicate:predicate]];
92     
93     // tableview刷新
94     [_tableView reloadData];
95 }
原文地址:https://www.cnblogs.com/fanwenzheIOS/p/4983054.html