搜索框的效果演示:
這個就是所謂的搜索框了,那么接下來我們看看如何使用代碼來實現這個功能.
我所使用的數據是英雄聯盟的英雄名單,是一個JSON數據的txt文件, JSON數據的處理代碼如下所示:
//獲取文件的路徑pathNSString *path = [[NSBundle mainBundle] pathForResource:@"heros" ofType:@"txt"];//將路徑下的文件轉換成NSData數據NSData *data = [NSData dataWithContentsOfFile:path];//將得到的NSdata數據進行JSON解析并返回一個結果數組resultid result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
我們再來看數據的層級關系:
這里解釋下,這個層級關系是通過在線代碼格式化網頁得到的,我們上一步所做的數據處理就是將原始數據進行處理,得到一個結果數組,他的層級關系和格式化后一樣,這樣就可以根據格式化網頁上的層級關系來進一步處理數據,將需要的內容放入數組或者字典(當然也可以直接打印result來看層級關系,看個人習慣).
那么我們所需要的內容就是字典中nick所對應的值,通過遍歷將其取出來放入數組中,這里將這個數組定義為屬性,在其他方法里會用到.
// 將搜索范圍的內容放入數組for (NSDictionary *diction in result) { [self.arrOfSeachBoxes addObject:diction[@"nick"]]; }
接下來我們創建一個UITableView用來顯示數據,搜索條需要用到的類是UISearchController
,先看看如何創建:
系統的注釋說的很清楚,如果想要在當前頁顯示搜索結果,這個方法的參數填nil即可,為了方便起見,聲明一個UISearchController
的屬性
@property (nonatomic, retain) UISearchController *searchController;
接下來是創建
// nil表示在當前頁面顯示搜索結果self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
UISearchController頭文件中被放在非常靠前的位置的是一個屬性
根據字面意思我們可以猜到這跟搜索結果的更新有關,就跟tableView
的reloadData
一個意思.那么很明顯,我們得簽協議<UISearchResultsUpdating
>,這個協議中只有一個必須要實現的方法.
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController;
頭文件如下圖所示:
---------這里是美麗的分割線---------
上面已經把所有關于搜索條的類和方法羅列了一下,下面來捋一捋
所有定義的屬性如下所示:
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;@endNS_ASSUME_NONNULL_END
數據處理相關代碼如下:
// 解析數據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的創建相關代碼如下:
// 創建self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];//searchBar的frameself.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相關的代碼如下:
// tableViewself.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協議方法代碼如下:
- (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
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {// 顯示搜索結果時if (self.searchController.active) { //以搜索結果的個數返回行數 return self.arrOfSeachResults.count;} //沒有搜索時顯示所有數據 return self.arrOfSeachBoxes.count;}
- (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;}
總結
以上就是如何實現IOS搜索欄及搜索關鍵字高亮的全部內容,感興趣的同學可以自己動手操作實現下,希望對大家的學習有所幫助。
新聞熱點
疑難解答