搜索框的效果演示:
?
?
這個就是所謂的搜索框了,那么接下來我們看看如何使用代碼來實現這個功能.
我所使用的數據是英雄聯盟的英雄名單,是一個JSON數據的txt文件, JSON數據的處理代碼如下所示:
1 2 3 4 5 6 | //獲取文件的路徑path NSString *path = [[NSBundle mainBundle] pathForResource:@"heros" ofType:@"txt"]; //將路徑下的文件轉換成NSData數據 NSData *data = [NSData dataWithContentsOfFile:path]; //將得到的NSdata數據進行JSON解析并返回一個結果數組result id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; |
我們再來看數據的層級關系:
?
這里解釋下,這個層級關系是通過在線代碼格式化網頁得到的,我們上一步所做的數據處理就是將原始數據進行處理,得到一個結果數組,他的層級關系和格式化后一樣,這樣就可以根據格式化網頁上的層級關系來進一步處理數據,將需要的內容放入數組或者字典(當然也可以直接打印result來看層級關系,看個人習慣).
那么我們所需要的內容就是字典中nick所對應的值,通過遍歷將其取出來放入數組中,這里將這個數組定義為屬性,在其他方法里會用到.
1 2 3 4 | // 將搜索范圍的內容放入數組 for (NSDictionary *diction in result) { ?? [self.arrOfSeachBoxes addObject:diction[@ "nick" ]]; ? } |
接下來我們創建一個UITableView用來顯示數據,搜索條需要用到的類是UISearchController
,先看看如何創建:
系統的注釋說的很清楚,如果想要在當前頁顯示搜索結果,這個方法的參數填nil即可,為了方便起見,聲明一個UISearchController
的屬性
1 | @property (nonatomic, retain) UISearchController *searchController; |
接下來是創建
1 2 | // nil表示在當前頁面顯示搜索結果 self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; |
UISearchController頭文件中被放在非常靠前的位置的是一個屬性
根據字面意思我們可以猜到這跟搜索結果的更新有關,就跟tableView
的reloadData
一個意思.那么很明顯,我們得簽協議<UISearchResultsUpdating
>,這個協議中只有一個必須要實現的方法.
1 | - ( void )updateSearchResultsForSearchController:(UISearchController *)searchController; |
頭文件如下圖所示:
---------這里是美麗的分割線---------
上面已經把所有關于搜索條的類和方法羅列了一下,下面來捋一捋
所有定義的屬性如下所示:
1 2 3 4 5 6 7 8 | NS_ASSUME_NONNULL_BEGIN @interface ViewController () <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating> @property (nonatomic, retain) NSMutableArray *arrOfSeachBoxes; /**< 搜索范圍 */ @property (nonatomic, retain) NSMutableArray *arrOfSeachResults; /**< 搜索結果 */ @property (nonatomic, retain) UISearchController *searchController; @property (nonatomic, retain) UITableView *tableView; @end NS_ASSUME_NONNULL_END |
數據處理相關代碼如下:
1 2 3 4 5 6 7 8 9 | // 解析數據 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]; // 將搜索范圍的內容放入數組 for (NSDictionary *dic in result) { ? [self.arrOfSeachBoxes addObject:dic[@ "nick" ]]; } |
和UISearchController的創建相關代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // 創建 self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; //searchBar的frame self.searchController.searchBar.frame = CGRectMake(0, 44, 0, 44); // 是否需要在輸入搜索內容時變暗 self.searchController.dimsBackgroundDuringPresentation = false ; self.searchController.searchBar.showsCancelButton = YES; /**< 取消按鈕 */ self.searchController.searchResultsUpdater = self; /**< 顯示搜索結果的VC */ self.searchController.active = YES; /**< 搜索結果顯示 */ |
和tableView相關的代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 | // 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協議方法代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | - ( void )updateSearchResultsForSearchController:(UISearchController *)searchController { //初始化存儲搜索結果的數組 self.arrOfSeachResults = [NSMutableArray array]; // 獲取關鍵字 NSPredicate *predicate = [NSPredicate predicateWithFormat:@ "SELF CONTAINS[c] %@" , searchController.searchBar.text]; // 用關鍵字過濾數組中的內容, 將過濾后的內容放入結果數組 self.arrOfSeachResults = [[self.arrOfSeachBoxes filteredArrayUsingPredicate:predicate] mutableCopy]; // 完成數據的過濾和存儲后刷新tableView. [self.tableView reloadData]; } |
tableView的DataSource
1 2 3 4 5 6 7 8 9 10 11 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // 顯示搜索結果時 if (self.searchController.active) { ? //以搜索結果的個數返回行數 ? return self.arrOfSeachResults.count; } ? //沒有搜索時顯示所有數據 ? return self.arrOfSeachBoxes.count; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@ "pool" ]; // 顯示搜索結果時 if (self.searchController.active) { // 原始搜索結果字符串. NSString *originResult = self.arrOfSeachResults[indexPath.row]; // 獲取關鍵字的位置 NSRange range = [originResult rangeOfString:self.searchController.searchBar.text]; // 轉換成可以操作的字符串類型. NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:originResult]; // 添加屬性(粗體) [attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:range]; // 關鍵字高亮 [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; } |