ios UISearchDisplayController 實現 UITableView 搜索功能


UISearchDisplayController 是蘋果專為 UITableView 搜索封裝的一個類。

里面內置了一個 UITableView 用於顯示搜索的結果。它可以和一個需要搜索功能的

controller 關聯起來,其它的像原 TableView 和搜索結果 TableView 的切換, mask 的顯示等等都

封裝好了,使用起來非常非常的簡單。特別是要實現全屏搜索時使用最多。

全屏搜索的意思是如果你用了  NavigationBar 當點擊搜索框時 TableView 會自動彈上去覆蓋

NavigationBar,達到一種全屏搜索的效果,這一切 UISearchDisplayController 都封裝好了,如果自己

寫就比較麻煩一些。

關鍵代碼:

@interface MainViewController : UITableViewController{
    NSArray *data;
    NSArray *filterData;
    UISearchDisplayController *searchDisplayController;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width
                                                                           , 44)];
    searchBar.placeholder = @"搜索";
    
    // 添加 searchbar 到 headerview
    self.tableView.tableHeaderView = searchBar;
    
    // 用 searchbar 初始化 SearchDisplayController
    // 並把 searchDisplayController 和當前 controller 關聯起來
    searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
    
    // searchResultsDataSource 就是 UITableViewDataSource
    searchDisplayController.searchResultsDataSource = self;
    // searchResultsDelegate 就是 UITableViewDelegate
    searchDisplayController.searchResultsDelegate = self;
}
/*
 * 如果原 TableView 和 SearchDisplayController 中的 TableView 的 delete 指向同一個對象
 * 需要在回調中區分出當前是哪個 TableView
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return data.count;
    }else{
        // 謂詞搜索
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self contains [cd] %@",searchDisplayController.searchBar.text];
        filterData =  [[NSArray alloc] initWithArray:[data filteredArrayUsingPredicate:predicate]];
        return filterData.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"mycell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    if (tableView == self.tableView) {
        cell.textLabel.text = data[indexPath.row];
    }else{
        cell.textLabel.text = filterData[indexPath.row];
    }
    
    return cell;
}

DEMO 下載:http://pan.baidu.com/s/1pJ8vvC3

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM