您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 程式設計技術

iOS 搜索框新寫法:UISearchController 完整實戰(取代 UISearchBar + UISearchDisplayController)

編輯:iOS 程式設計技術

在 iOS 8.0 及以後的系統中,我們可以用 UISearchController 非常輕鬆地在 UITableView 上添加搜索框。而在更早的版本裡,只能採用 UISearchBar + UISearchDisplayController 的組合方式,配置繁瑣且容易出錯。

一、聲明屬性

@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) NSMutableArray *allCities;     // 所有城市
@property (strong, nonatomic) NSMutableArray *filteredCities; // 根據searchController搜索的城市

二、初始化 UISearchController

在 viewDidLoad 中完成初始化:

self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = false;
[self.searchController.searchBar sizeToFit];
self.searchController.searchBar.backgroundColor = UIColorFromHex(0xdcdcdc);
self.tableView.tableHeaderView = self.searchController.searchBar;

三、實現 UISearchResultsUpdating 協議

使用 UISearchController 需要遵循 UISearchResultsUpdating 協議並實現其中的方法:

#pragma mark - searchController delegate
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    [self.filteredCities removeAllObjects];
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@",
                                    self.searchController.searchBar.text];
    self.filteredCities = [[self.allCities filteredArrayUsingPredicate:searchPredicate] mutableCopy];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

只要 searchBar 中的內容發生變化,這個方法就會被調用。在裡面我們用 NSPredicate 設置過濾條件——contains[c] 中的 [c] 表示忽略大小寫。

四、同步更新 UITableView

引入搜索框之後,列表的數據源也要相應變化:cell 中到底展示 allCities 還是 filteredCities?判斷依據是 UISearchController 的 active 屬性,也就是搜索框是否處於激活狀態。Table View 的多個方法都需要做這個判斷:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (!self.searchController.active) {
        return self.cityKeys.count;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.searchController.active) {
        NSString *key = self.cityKeys[section];
        NSArray *citySection = self.cityDict[key];
        return citySection.count;
    } else {
        return self.filteredCities.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                     reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    // 根據UISearchController的active屬性來判斷cell中的內容
    if (!self.searchController.active) {
        NSString *key = self.cityKeys[indexPath.section];
        cell.textLabel.text = [self.cityDict[key] objectAtIndex:indexPath.row];
    } else {
        cell.textLabel.text = self.filteredCities[indexPath.row];
    }
    return cell;
}

五、離開頁面時移除搜索框

這一點很容易被忽略:必須在 viewWillDisappear 中主動移除 UISearchController,否則切換到下一個界面時,搜索框還會短暫殘留一幀。

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}

小結

整體流程可以概括為四步:聲明並初始化 UISearchController、實現 updateSearchResultsForSearchController: 做數據過濾、根據 active 狀態切換列表數據源、頁面離開時清理搜索框。相比舊方案,新寫法 API 更清晰,也不用手動管理搜索框的顯示與動畫。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved