UI_UISearchController实现搜索功能

本文详细介绍了如何使用UISearchController实现iOS设备上的搜索功能,包括初始化方法、常用属性和代理方法,以及如何通过谓词筛选数据源并更新搜索结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<ObjectType> *)filteredArrayUsingPredicate:(NSPredicate *)predicate;   

谓词格式

  • BEGINSWITH:搜索结果的字符串是以搜索框里的字符开头的

  • ENDSWITH:搜索结果的字符串是以搜索框里的字符结尾的

  • CONTAINS:搜索结果的字符串包含搜索框里的字符

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

案例

案例主要实现字体搜索,搜索控制器的刷新者即为当前视图控制器,效果如下:

这里写图片描述

  • 代码示例:
#import "ViewController.h"  

static NSString *const kUITableViewCellIdentifier = @"cellIdentifier";  

@interface ViewController ()  <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>{  

    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 - Init methods  
- (void)initializeDataSource {  

    // 初始化数据源  
    _dataSource = [NSMutableArray arrayWithArray:[UIFont familyNames]];  

}  

- (void)initializeUserInterface {  

    self.automaticallyAdjustsScrollViewInsets = NO;  
    [self.view addSubview:self.tableView];  
    self.tableView.tableHeaderView = self.searchController.searchBar;  

}  

#pragma mark - <UITableViewDelegate, UITableViewDataSource>  
- (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:kUITableViewCellIdentifier];  
    if (!cell) {  
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kUITableViewCellIdentifier];  
    }  

    // 如果用户正在搜索,则返回搜索结果对应的数据,否则直接返回数据数组对应的数据;  
    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 - <UISearchResultsUpdating>  
// 每次更新搜索框里的文字,就会调用这个方法  
- (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 - Getter methods  

- (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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值