標籤:
搜尋功能,基本每個app標配。
實現起來很簡單,但是iOS8後蘋果建議使用UISearchController,官方Demo:Table Search with UISearchController
實際開發基本也都還是用的老的UISearchDisplayController+UISearchBar的方案,因為要照顧一些版本低的使用者。
發現時間長沒寫都忘記差不多了,閑暇之餘,一起整理下,方便以後翻閱。
這篇先從UISearchDisplayController開始。比較簡單,就不羅嗦了,直接貼代碼。
- UITableView步驟略去。
建立一個UISearchBar
1 _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];2 _searchBar.delegate = self;3 _searchBar.placeholder = @"搜尋";4 _searchBar.backgroundColor = [UIColor clearColor];
根據searchBar建立一個UISearchDisplayController
1 _searchDisplayCtl = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];2 _searchDisplayCtl.delegate = self;3 _searchDisplayCtl.searchResultsDataSource = self;4 _searchDisplayCtl.searchResultsDelegate = self;
設定tableView的tableHearderView為searchBar
1 _tableView.tableHeaderView = _searchBar;
更改searchBar的Cancel按鈕為“取消”,注意:因為iOS7後和之前的階層不同,iOS7前遍曆一次即可拿到,iOS7後需要遍曆兩次,在UISearchBar的代理方法中設定
1 - (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar 2 { 3 for (id sView in searchBar.subviews) 4 { 5 if ([sView isKindOfClass:[UIButton class]]) 6 { 7 [(UIButton *)sView setTitle:@"取消" forState:UIControlStateNormal]; 8 break; 9 }10 for (id ssView in [sView subviews])11 {12 if ([ssView isKindOfClass:[UIButton class]])13 {14 [(UIButton *)ssView setTitle:@"取消" forState:UIControlStateNormal];15 }16 }17 }18 19 // 預設只要已進入搜尋狀態,cancel按鈕就會出現,20 // 但是不知道為什麼有時候沒出來,嚴謹性,我們就自己加上下面這段。21 [searchBar setShowsCancelButton:YES animated:YES];22 }
- 最後一步,搜尋展示結果。UISearchDisplayController代理中處理
1 #pragma mark - UISearchDisplayController 2 - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString 3 { 4 [_resultList removeAllObjects]; 5 6 for (NSString *subString in _dataList) 7 { 8 if ([subString rangeOfString:searchString].location != NSNotFound) 9 {10 [_resultList addObject:subString];11 }12 }13 14 return YES;15 }
最簡便的一個搜尋完成了,UISearchBar和UISearchDisplayController還提供給我們很多其他的代理方法,都是些常規讀名取意型的,就不一一介紹了,實際用到了看下就可以了。蘋果封裝的已經很好,而且UI也蠻漂亮的,所以我們也沒必要自己寫一個。
不過,實際過程中有兩點可能會用到。網上也挺多資料,大概整理下。方便以後尋找使用。
項目中可能會有需要我們改變其背景顏色或者背景圖片的需求,其大概實現原理類似更改cancel按鈕的title。需要注意的還是iOS版本不同,階層不同
UISearchDisplayController搜尋(iOS8前)