[iOS]系統(tǒng)UISearchController詳解

UISearchControlleriOS 8 之后推出的一個(gè)新的控件, 用于創(chuàng)建搜索條, 及管理搜索事件, 使用這個(gè), 我們可以很容易的創(chuàng)建屬于自己的搜索框, 下面就來看看這個(gè)控件的一些使用.

一. 基本使用( 同一個(gè)控制器 )

UISearchController 一般是和 UITableView 結(jié)合使用, 很少會(huì)單獨(dú)使用他, 而且使用 UITableView 來展示數(shù)據(jù), 也是最佳的選擇.
他的API十分簡(jiǎn)單:

// 初始化方法, 參數(shù)是展示搜索結(jié)果的控制器, 如果是在當(dāng)前控制器展示搜索結(jié)果, 就傳nil
- (instancetype)initWithSearchResultsController:(nullable UIViewController *)searchResultsController;

// 負(fù)責(zé)更新搜索結(jié)果的代理, 需要遵循 UISearchResultsUpdating 協(xié)議
@property (nullable, nonatomic, weak) id <UISearchResultsUpdating> searchResultsUpdater;

// 搜索控制器是否是活躍狀態(tài), 當(dāng)在一個(gè)控制器展示搜索結(jié)果的時(shí)候, 可以此來判斷返回的數(shù)據(jù)源
@property (nonatomic, assign, getter = isActive) BOOL active;
// 控制器代理  遵循 UISearchControllerDelegate協(xié)議
@property (nullable, nonatomic, weak) id <UISearchControllerDelegate> delegate;
// 當(dāng)搜索框激活時(shí), 是否添加一個(gè)透明視圖
@property (nonatomic, assign) BOOL dimsBackgroundDuringPresentation __TVOS_PROHIBITED; 
@property (nonatomic, assign) BOOL obscuresBackgroundDuringPresentation NS_AVAILABLE_IOS(9_1); // default is YES
// 當(dāng)搜索框激活時(shí), 是否隱藏導(dǎo)航條
@property (nonatomic, assign) BOOL hidesNavigationBarDuringPresentation;     // default is YES

@property (nullable, nonatomic, strong, readonly) UIViewController *searchResultsController;
@property (nonatomic, strong, readonly) UISearchBar *searchBar;

PS : 需要注意的是, UISearchController 在使用的時(shí)候, 需要設(shè)置為全局的變量或者控制器屬性, 使其生命周期與控制器相同; 如果設(shè)置為局部變量, 會(huì)提前銷毀, 導(dǎo)致無法使用.

我們先聲明一些屬性:

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UISearchController *searchController;
// 數(shù)據(jù)源數(shù)組
@property (nonatomic, strong) NSMutableArray *datas;
// 搜索結(jié)果數(shù)組
@property (nonatomic, strong) NSMutableArray *results;

初始化相關(guān)屬性:

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
    }
    
    return _tableView;
}

- (NSMutableArray *)datas {
    if (_datas == nil) {
        _datas = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _datas;
}

- (NSMutableArray *)results {
    if (_results == nil) {
        _results = [NSMutableArray arrayWithCapacity:0];
    }
    
    return _results;
}

然后, 實(shí)現(xiàn) tableViewsearchController 的一些協(xié)議, 及其方法:

<UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>

創(chuàng)建 UISearchController:

// 創(chuàng)建UISearchController, 這里使用當(dāng)前控制器來展示結(jié)果
    UISearchController *search = [[UISearchController alloc]initWithSearchResultsController:nil];
    // 設(shè)置結(jié)果更新代理
    search.searchResultsUpdater = self;
    // 因?yàn)樵诋?dāng)前控制器展示結(jié)果, 所以不需要這個(gè)透明視圖
    search.dimsBackgroundDuringPresentation = NO;
    self.searchController = search;
    // 將searchBar賦值給tableView的tableHeaderView
    self.tableView.tableHeaderView = search.searchBar;

實(shí)現(xiàn)tableView的數(shù)據(jù)源及代理方法:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // 這里通過searchController的active屬性來區(qū)分展示數(shù)據(jù)源是哪個(gè)
    if (self.searchController.active) {
        
        return self.results.count ;
    }
    
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
    }
    
    // 這里通過searchController的active屬性來區(qū)分展示數(shù)據(jù)源是哪個(gè)
    if (self.searchController.active ) {
        
        cell.textLabel.text = [self.results objectAtIndex:indexPath.row];
    } else {
        
        cell.textLabel.text = [self.datas objectAtIndex:indexPath.row];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.searchController.active) {
        NSLog(@"選擇了搜索結(jié)果中的%@", [self.results objectAtIndex:indexPath.row]);
    } else {
        
        NSLog(@"選擇了列表中的%@", [self.datas objectAtIndex:indexPath.row]);
    }
    
}

最后實(shí)現(xiàn) UISearchController 的協(xié)議 UISearchResultsUpdating方法:

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *inputStr = searchController.searchBar.text ;
    if (self.results.count > 0) {
        [self.results removeAllObjects];
    }
    for (NSString *str in self.datas) {
        
        if ([str.lowercaseString rangeOfString:inputStr.lowercaseString].location != NSNotFound) {
            
            [self.results addObject:str];
        }
    }
    
    [self.tableView reloadData];
}

這里我只是簡(jiǎn)單的過濾了一遍數(shù)據(jù)源, 把數(shù)據(jù)源中包含輸入字符的內(nèi)容, 添加到搜索結(jié)果的數(shù)組results中, 然后刷新表格來展示搜索結(jié)果:

效果圖

如果我們想在開始輸入文字之前或者之后做一些操作, 可以實(shí)現(xiàn)searchBar的相關(guān)代理方法;
需要注意的是 : 這里當(dāng)搜索框激活時(shí), 隱藏導(dǎo)航的動(dòng)畫, 這是在和系統(tǒng)導(dǎo)航結(jié)合使用, 并且searchController的屬性hidesNavigationBarDuringPresentationYES的情況下, 才會(huì)有的動(dòng)畫效果, 如果使用了自定義的導(dǎo)航, 那就沒有這個(gè)效果了, 但是我們可以在 searchBar 的代理方法里, 設(shè)置相關(guān)的動(dòng)畫效果, 但是整體還是沒有系統(tǒng)動(dòng)畫自然.

二. 使用自定義導(dǎo)航條

我們吧上面的代碼做一下修改,:

// 視圖顯示的時(shí)候, 隱藏系統(tǒng)導(dǎo)航  使用自定義導(dǎo)航
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.navigationController) {
        
        self.navigationController.navigationBarHidden = YES;
    }
}
// 視圖消失的時(shí)候, 將系統(tǒng)導(dǎo)航恢復(fù)
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (self.navigationController) {
        self.navigationController.navigationBarHidden = NO;
    }
}

然后, 自定義一個(gè)導(dǎo)航條:

- (UIView *)customNavBar {
    if (_customNavBar == nil) {
        _customNavBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
        _customNavBar.backgroundColor = [UIColor whiteColor];
        
        [self.view addSubview:_customNavBar];
    }
    
    return _customNavBar;
}

添加相關(guān)元素, 這里只是添加了一個(gè)返回按鈕:

- (void)setupNavBar {
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 20, 80, 44);
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.customNavBar addSubview:backBtn];
}

- (void)backBtnClick {
    
    [self.navigationController popViewControllerAnimated:YES];
}

這時(shí)候的效果是這樣的:

可以看到, 這里并不難自動(dòng)隱藏自定義的導(dǎo)航, 這需要我們自己處理;
剩下的就是怎么來處理導(dǎo)航條的問題, 這時(shí)候就用到了searchBar的代理方法:

#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
}

我這里, 主要是在上面的這兩個(gè)代理方法里處理的, 具體的實(shí)現(xiàn)如下:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
    CGRect barFrame = self.customNavBar.frame;
    // 移動(dòng)到屏幕上方
    barFrame.origin.y = - 64;
    
    
    // 調(diào)整tableView的frame為全屏
    CGRect tableFrame = self.tableView.frame;
    tableFrame.origin.y = 20;
    tableFrame.size.height = self.view.frame.size.height -20;
這里Y坐標(biāo)從20開始, 是因?yàn)? searchBar的背景視圖會(huì)多出20的高度, 而tableView的tableHeaderView并沒有相應(yīng)增加, 所以這里強(qiáng)制空出20像素, 防止searchBar遮擋cell
    
    self.customNavBar.frame = barFrame;
    self.tableView.frame = tableFrame;
    [UIView animateWithDuration:0.4 animations:^{
        
        [self.view layoutIfNeeded];
        [self.tableView layoutIfNeeded];
    }];
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    
    
    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
    CGRect barFrame = self.customNavBar.frame;
    // 恢復(fù)
    barFrame.origin.y = 0;
    
    
    // 調(diào)整tableView的frame為全屏
    CGRect tableFrame = self.tableView.frame;
    tableFrame.origin.y = 64;
    tableFrame.size.height = self.view.frame.size.height - 64;
    
    
    [UIView animateWithDuration:0.4 animations:^{
        
        self.customNavBar.frame = barFrame;
        self.tableView.frame = tableFrame;
    }];
}

上面的開始編輯時(shí), 設(shè)置 tableView Y 坐標(biāo)時(shí)多出了20, 這里Y坐標(biāo)從20開始, 是因?yàn)? searchBar 的背景視圖會(huì)多出20的高度, 而tableView** 的 tableHeaderView 并沒有相應(yīng)增加, 所以這里強(qiáng)制空出20像素, 防止 searchBar 遮擋cell;這時(shí)的效果圖如下:


可以看出還是有些突兀, 以上只是大致思路, 具體實(shí)現(xiàn)細(xì)節(jié)還需要再做優(yōu)化.

三. 使用單獨(dú)的控制器來展示搜索結(jié)果

以上搜索結(jié)果的展示都是在一個(gè)控制器里進(jìn)行的, 使用searchControlleractive屬性來區(qū)分?jǐn)?shù)據(jù)源; 我們還可以使用兩個(gè)控制器來進(jìn)行, 一個(gè)展示原始數(shù)據(jù), 一個(gè)來展示搜索的結(jié)果;
這其實(shí)只是在初始化searchController的時(shí)候有些區(qū)別, 然后兩個(gè)控制器分別管理自己的數(shù)據(jù)源即可, 這里直接給出代碼:
初始化:

 // 創(chuàng)建用于展示搜索結(jié)果的控制器
    LZResultDisplayController *result = [[LZResultDisplayController alloc]init];
    // 創(chuàng)建搜索框
    UISearchController *search = [[UISearchController alloc]initWithSearchResultsController:result];

    self.tableView.tableHeaderView = search.searchBar;
    
    search.searchResultsUpdater = result;
    
    self.searchController = search;

然后在 LZResultDisplayController.h 遵循協(xié)議UISearchResultsUpdating :

@interface LZResultDisplayController : UIViewController<UISearchResultsUpdating>

@end

實(shí)現(xiàn)協(xié)議方法:

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    // 這里處理過濾數(shù)據(jù)源的邏輯
NSString *inputStr = searchController.searchBar.text ;
    if (self.results.count > 0) {
        [self.results removeAllObjects];
    }
    for (NSString *str in self.datas) {
        
        if ([str.lowercaseString rangeOfString:inputStr.lowercaseString].location != NSNotFound) {
            
            [self.results addObject:str];
        }
    }
    // 然后刷新表格
    [self.tableView reloadData];
}

其他的要做的, 就是各自管理分配自己的數(shù)據(jù)源了, 效果圖如下:

這里的綠色部分只是個(gè)區(qū)頭, 因?yàn)槭褂玫?strong>UITableViewController, 沒有做特別的處理.

這里有一個(gè)demo, 有需要的可以參考LZSearchController

關(guān)于searchBar的相關(guān)設(shè)置, 可參考筆者的另一篇文章[iOS]關(guān)于UISearchBar, 看這個(gè)就夠了;

(完)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容