如何實現(xiàn)IOS_SearchBar搜索欄及關(guān)鍵字高亮
搜索框的效果演示:
這個就是所謂的搜索框了,那么接下來我們看看如何使用代碼來實現(xiàn)這個功能.
我所使用的數(shù)據(jù)是英雄聯(lián)盟的英雄名單,是一個JSON數(shù)據(jù)的txt文件, JSON數(shù)據(jù)的處理代碼如下所示:
//獲取文件的路徑path NSString *path = [[NSBundle mainBundle] pathForResource:@"heros" ofType:@"txt"]; //將路徑下的文件轉(zhuǎn)換成NSData數(shù)據(jù) NSData *data = [NSData dataWithContentsOfFile:path]; //將得到的NSdata數(shù)據(jù)進行JSON解析并返回一個結(jié)果數(shù)組result id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
我們再來看數(shù)據(jù)的層級關(guān)系:
這里解釋下,這個層級關(guān)系是通過在線代碼格式化網(wǎng)頁得到的,我們上一步所做的數(shù)據(jù)處理就是將原始數(shù)據(jù)進行處理,得到一個結(jié)果數(shù)組,他的層級關(guān)系和格式化后一樣,這樣就可以根據(jù)格式化網(wǎng)頁上的層級關(guān)系來進一步處理數(shù)據(jù),將需要的內(nèi)容放入數(shù)組或者字典(當(dāng)然也可以直接打印result來看層級關(guān)系,看個人習(xí)慣).
那么我們所需要的內(nèi)容就是字典中nick所對應(yīng)的值,通過遍歷將其取出來放入數(shù)組中,這里將這個數(shù)組定義為屬性,在其他方法里會用到.
// 將搜索范圍的內(nèi)容放入數(shù)組 for (NSDictionary *diction in result) { [self.arrOfSeachBoxes addObject:diction[@"nick"]]; }
接下來我們創(chuàng)建一個UITableView用來顯示數(shù)據(jù),搜索條需要用到的類是UISearchController
,先看看如何創(chuàng)建:
系統(tǒng)的注釋說的很清楚,如果想要在當(dāng)前頁顯示搜索結(jié)果,這個方法的參數(shù)填nil即可,為了方便起見,聲明一個UISearchController
的屬性
@property (nonatomic, retain) UISearchController *searchController;
接下來是創(chuàng)建
// nil表示在當(dāng)前頁面顯示搜索結(jié)果 self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
UISearchController頭文件中被放在非??壳暗奈恢玫氖且粋€屬性
根據(jù)字面意思我們可以猜到這跟搜索結(jié)果的更新有關(guān),就跟tableView
的reloadData
一個意思.那么很明顯,我們得簽協(xié)議<UISearchResultsUpdating
>,這個協(xié)議中只有一個必須要實現(xiàn)的方法.
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController;
頭文件如下圖所示:
---------這里是美麗的分割線---------
上面已經(jīng)把所有關(guān)于搜索條的類和方法羅列了一下,下面來捋一捋
所有定義的屬性如下所示:
NS_ASSUME_NONNULL_BEGIN @interface ViewController () <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating> @property (nonatomic, retain) NSMutableArray *arrOfSeachBoxes;/**< 搜索范圍 */ @property (nonatomic, retain) NSMutableArray *arrOfSeachResults;/**< 搜索結(jié)果 */ @property (nonatomic, retain) UISearchController *searchController; @property (nonatomic, retain) UITableView *tableView; @end NS_ASSUME_NONNULL_END
數(shù)據(jù)處理相關(guān)代碼如下:
// 解析數(shù)據(jù) NSString *path = [[NSBundle mainBundle] pathForResource:@"heros" ofType:@"txt"]; NSData *data = [NSData dataWithContentsOfFile:path]; id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; self.arrOfSeachBoxes = [NSMutableArray array]; // 將搜索范圍的內(nèi)容放入數(shù)組 for (NSDictionary *dic in result) { [self.arrOfSeachBoxes addObject:dic[@"nick"]]; }
和UISearchController的創(chuàng)建相關(guān)代碼如下:
// 創(chuàng)建 self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; //searchBar的frame self.searchController.searchBar.frame = CGRectMake(0, 44, 0, 44); // 是否需要在輸入搜索內(nèi)容時變暗 self.searchController.dimsBackgroundDuringPresentation = false; self.searchController.searchBar.showsCancelButton = YES;/**< 取消按鈕 */ self.searchController.searchResultsUpdater = self;/**< 顯示搜索結(jié)果的VC */ self.searchController.active = YES;/**< 搜索結(jié)果顯示 */
和tableView相關(guān)的代碼如下:
// tableView self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, self.view.bounds.size.height - 20) style:UITableViewStylePlain]; [self.view addSubview:self.tableView]; self.tableView.delegate = self; self.tableView.dataSource = self; [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"pool"]; //將SearchBar放在tableView的頭部視圖 self.tableView.tableHeaderView = self.searchController.searchBar;
UISearchResultsUpdating協(xié)議方法代碼如下:
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController { //初始化存儲搜索結(jié)果的數(shù)組 self.arrOfSeachResults = [NSMutableArray array]; // 獲取關(guān)鍵字 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchController.searchBar.text]; // 用關(guān)鍵字過濾數(shù)組中的內(nèi)容, 將過濾后的內(nèi)容放入結(jié)果數(shù)組 self.arrOfSeachResults = [[self.arrOfSeachBoxes filteredArrayUsingPredicate:predicate] mutableCopy]; // 完成數(shù)據(jù)的過濾和存儲后刷新tableView. [self.tableView reloadData]; }
tableView的DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // 顯示搜索結(jié)果時 if (self.searchController.active) { //以搜索結(jié)果的個數(shù)返回行數(shù) return self.arrOfSeachResults.count; } //沒有搜索時顯示所有數(shù)據(jù) return self.arrOfSeachBoxes.count; }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"]; // 顯示搜索結(jié)果時 if (self.searchController.active) { // 原始搜索結(jié)果字符串. NSString *originResult = self.arrOfSeachResults[indexPath.row]; // 獲取關(guān)鍵字的位置 NSRange range = [originResult rangeOfString:self.searchController.searchBar.text]; // 轉(zhuǎn)換成可以操作的字符串類型. NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:originResult]; // 添加屬性(粗體) [attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:range]; // 關(guān)鍵字高亮 [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range]; // 將帶屬性的字符串添加到cell.textLabel上. [cell.textLabel setAttributedText:attribute]; cell.textLabel.text = self.arrOfSeachResults[indexPath.row]; } else { cell.textLabel.text = self.arrOfSeachBoxes[indexPath.row]; } return cell; }
總結(jié)
以上就是如何實現(xiàn)IOS搜索欄及搜索關(guān)鍵字高亮的全部內(nèi)容,感興趣的同學(xué)可以自己動手操作實現(xiàn)下,希望對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
實例講解iOS中的UIPageViewController翻頁視圖控制器
UIPageViewController更像是一個視圖容器,將每頁不同的ViewController整合,這里我們將以實例講解iOS中的UIPageViewController翻頁視圖控制器:2016-06-06Framework中實現(xiàn)OC和Swift的混編方案
這篇文章主要為大家介紹了Framework中實現(xiàn)OC和Swift的混編方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01iOS App開發(fā)中Objective-C使用正則表達式進行匹配的方法
這篇文章主要介紹了iOS App開發(fā)中Objective-C使用正則表達式進行匹配的方法,文中舉了在iOS中驗證用戶郵箱與手機號的例子,非常實用,匹配需要的朋友可以參考下2016-05-05