UI:UISearchController 搜索

初始化方法

- (instancetype)initWithSearchResultsController:(nullable UIViewController *)searchResultsController;

常用属性

  searchResultsUpdater:设置搜索结果刷新者(设置该属性需遵守 UISearchResultsUpdating协议)
  active:设置(获取)当前搜索状态
  delegate:设置代理
  dimsBackgroundDuringPresentation:设置是否在搜索时显示半透明背景
  hidesNavigationBarDuringPresentation:设置是否在搜索时隐藏导航栏
  searchResultsController:搜索结果控制器
  searchBar:搜索框

UISearchBar

  • 常用属性

    autocapitalizationType:设置自动大小写样式
    tintColor:设置前景色
    barTintColor:设置背景颜色
    searchBarStyle:设置搜索框样式
    translucent:设置是否半透明
    

UISearchResultsUpdating

  • UISearchResultsUpdating是一个结果刷新协议,其提供的方法如下
// 每次更新搜索框里的文字,就会调用这个方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController;

谓词

  • NSPredicate 创建谓词

    谓词创建方法:
    +(NSPredicate *)predicateWithFormat:(NSString *)predicateFormat, ...;
    // 示例:创建一个以‘A’字母开头的谓词判断
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH [CD] %@", @"A"];
    
  • 根据谓词判断在数组中进行搜索,得到结果数组的方法如下:

    - (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate; 
    
  • 代码示例:

#import "ViewController.h"

static NSString *const kReusableCellIdentifier = @"identifier";

@interface ViewController ()  {

    NSMutableArray *_dataSource; /**< 数据源 */
    NSMutableArray *_searchResults; /**< 搜索结果 */
}

@property (nonatomic, strong) UITableView *tableView; /**< 表格视图 */
@property (nonatomic, strong) UISearchController *searchController; /**< 搜索控制器 */

- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserInterface];
}

#pragma mark *** Initialize methods ***

- (void)initializeDataSource {
    // 初始化数据源
    _dataSource = [NSMutableArray arrayWithArray:[UIFont familyNames]];
}

- (void)initializeUserInterface {

    self.view.backgroundColor = [UIColor whiteColor];

    // 关闭系统自动偏移
    self.automaticallyAdjustsScrollViewInsets = NO;

    // 加载表格视图
    [self.view addSubview:self.tableView];

    // 添加导航栏
    self.tableView.tableHeaderView = self.searchController.searchBar;

}

#pragma mark ***  ***

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // 如果用户正在搜索,则返回搜索结果的count,否则直接返回数据源数组的count;
    if (self.searchController.active) {
        return _searchResults.count;
    }else {
        return _dataSource.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReusableCellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kReusableCellIdentifier];
    }

    // 如果用户正在搜索,则返回搜索结果对应的数据,否则直接返回数据数组对应的数据;
    if (self.searchController.active) {
        cell.textLabel.text = _searchResults[indexPath.row];
    }else {
        cell.textLabel.text = _dataSource[indexPath.row];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // 取消选中
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (self.searchController.active) {
        NSLog(@"%@", _searchResults[indexPath.row]);
    }else {
        NSLog(@"%@", _dataSource[indexPath.row]);
    }

    // 停止搜索
    self.searchController.active = NO;
}

#pragma mark ***  ***

// 每次更新搜索框里的文字,就会调用这个方法
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    // 获取搜索框里地字符串
    NSString *searchString = searchController.searchBar.text;

    // 谓词
    /**
     1.BEGINSWITH : 搜索结果的字符串是以搜索框里的字符开头的
     2.ENDSWITH   : 搜索结果的字符串是以搜索框里的字符结尾的
     3.CONTAINS   : 搜索结果的字符串包含搜索框里的字符

    [c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写,也不区分发音符号。

     */

    // 创建谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH [CD] %@", searchString];

    // 如果搜索框里有文字,就按谓词的匹配结果初始化结果数组,否则,就用字体列表数组初始化结果数组。
    if (_searchResults != nil && searchString.length > 0) {
        [_searchResults removeAllObjects];
        _searchResults = [NSMutableArray arrayWithArray:[_dataSource filteredArrayUsingPredicate:predicate]];
    } else if (searchString.length == 0) {
        _searchResults = [NSMutableArray arrayWithArray:_dataSource];
    }

    // 刷新表格视图
    [_tableView reloadData];
}


#pragma mark *** Getters ***

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - 64) style:UITableViewStylePlain];
        // 设置代理
        _tableView.delegate = self;
        // 设置数据源
        _tableView.dataSource = self;
        // 设置单元格高度
        _tableView.rowHeight = 50;
    }
    return _tableView;
}


- (UISearchController *)searchController {
    if (!_searchController) {
        // 初始化搜索控制器
        _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        // 设置代理
        _searchController.searchResultsUpdater = self;
        // 设置半透明背景,当设置当前视图控制器作为搜索结果的视图控制器时,要设为NO;
        _searchController.dimsBackgroundDuringPresentation = NO;
        // 隐藏导航栏
        _searchController.hidesNavigationBarDuringPresentation = YES;
        // 关掉自动大写锁定
        _searchController.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
        // 设置searchBar的frame
        _searchController.searchBar.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 44);
    }
    return _searchController;
}

@end

你可能感兴趣的:(UI:UISearchController 搜索)