1衰絮、系統(tǒng)自帶搜索框
2吻育、謂詞的使用
使用系統(tǒng)自帶搜索框UISearchController做个, 使用這個(gè)協(xié)議UISearchResultsUpdating 炼幔,dataArray存放原來(lái)的數(shù)據(jù)秋茫,searchArray存放過(guò)濾后的數(shù)據(jù)
//
// ViewController.m
// Search
//
// Created by lxy on 16/5/29.
// Copyright ? 2016年 lxy. All rights reserved.
//
#import "ViewController.h"
@interface ViewController () <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
/** 源數(shù)據(jù) */
@property (nonatomic, strong) NSMutableArray *dataArray;
/** 搜索結(jié)果數(shù)組 */
@property (nonatomic, strong) NSMutableArray *searchArray;
/** 搜索框 */
@property (nonatomic, strong) UISearchController *searchC;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化數(shù)據(jù)
[self setupData];
// 創(chuàng)建搜索框架
[self setupSearchC];
}
#pragma mark - 搜索框
- (void)setupSearchC {
_searchC = [[UISearchController alloc] initWithSearchResultsController:nil];
_searchC.searchBar.frame = CGRectMake(0, 0, self.view.frame.size.width, 50);
// 設(shè)置代理
_searchC.searchResultsUpdater = self;
// 不變灰
// _searchC.dimsBackgroundDuringPresentation = NO;
self.tableView.tableHeaderView = _searchC.searchBar;
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
// 獲取搜索框里輸入的內(nèi)容
NSString *str = searchController.searchBar.text;
NSLog(@"%@", str);
// 過(guò)濾條件 [c] 不區(qū)分大小寫 * 通配符
NSString *p = [NSString stringWithFormat:@"SELF LIKE[c] '*%@*'", str];
// 創(chuàng)建謂詞
NSPredicate *predicate = [NSPredicate predicateWithFormat:p];
// 清空搜索數(shù)組
[_searchArray removeAllObjects];
self.searchArray = [NSMutableArray arrayWithArray:[_dataArray filteredArrayUsingPredicate:predicate]];
[self.tableView reloadData];
}
#pragma mark - 初始化數(shù)據(jù)
- (void)setupData {
// 獲取數(shù)據(jù)
NSString *path = [[NSBundle mainBundle] pathForResource:@"search" ofType:@"plist"];
_dataArray = [NSMutableArray arrayWithContentsOfFile:path];
}
#pragma mark - 數(shù)據(jù)源
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (_searchC.active) {
return _searchArray.count;
} else {
return _dataArray.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
if (_searchC.active) {
cell.textLabel.text = _searchArray[indexPath.row];
} else {
cell.textLabel.text = _dataArray[indexPath.row];
}
return cell;
}
// 返回cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 64;
}
@end