UISearchDisplayController - how to preload searchResultTableView

前端 未结 8 1227
深忆病人
深忆病人 2020-12-08 10:56

I want to show some default content when the user taps the Searchbar, but before any text is entered.

I have a solution working using settext:

- (voi         


        
8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 11:13

    Here's a way to pre-populate the searchController.

    // 1. Save previous search results as soon as user enters text

    - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
    {
        // save searchString
    
        return YES;
    }
    

    // 2. load previous search string at startup

    - (void)viewDidLoad 
    {
        // create data source for table view
        // searchData may be a NSMutableArray property defined in your interface
    
        self.searchData = // search your master list for searchString
    
        // or create your own list using any search criteria you want
    
        // or you may act depending on user preference
        if(!showPreviousSearch)
        {
            // [searchData removeAllObjects];
        }
    }
    

    // 3. provide correct data source when asked

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) 
        {
            ...
        }
    
        NSMutableArray *dataSource = nil;
        if (tableView == [[self searchDisplayController] searchResultsTableView])
        {
            dataSource = self.searchData;
        }
        else
        {
            dataSource = self.masterData;
        }
    
        ...
    
        return cell;
    }
    

    // Hope this helps.

    Thanks

提交回复
热议问题