为什么没有调用方法updateSearchResultsForSearchController?

时间:2015-06-10 07:49:31

标签: swift uisearchcontroller

我有一个维护食谱集合的UICollectionViewController。

class RecipesViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource  {

另一个UICollectionViewController用于维护搜索结果,同样实现UISearchResultsUpdating:

class SearchResultsController: UICollectionViewController, UISearchResultsUpdating,UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { ...

我需要搜索集合,所以我有一个成员进入RecipesViewController

var searchController: UISearchController!

也是这样发起的:

let resultsController = SearchResultsController()
resultsController.recipes = recipes
resultsController.filteredResults = recipes

searchController = UISearchController(searchResultsController: resultsController)
searchController.searchResultsUpdater = resultsController

我将来自searchController的UISearchBar放入RecipesViewController的标题中。

我的问题是,在将文本输入searchBar时,SearchResultsController没有更新。方法updateSearchResultsForSearchController甚至没有被调用。

2 个答案:

答案 0 :(得分:2)

@interface YourViewController_CollectionResults () <UISearchResultsUpdating>

@end

@implementation YourViewController_CollectionResults
- (void)viewDidLoad {

    [super viewDidLoad];

    // The collection view controller is in a nav controller, and so the containing nav controller is the 'search results controller'
    UINavigationController *searchResultsController = [[self storyboard] instantiateViewControllerWithIdentifier:@"CollectionSearchResultsNavController"];

    self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];

    //It's really import that you class implement <UISearchResultsUpdating> 
    self.searchController.searchResultsUpdater = self;

    self.tableView.tableHeaderView = self.searchController.searchBar;

    self.definesPresentationContext = YES;

}

你在这个github中有一个例子

Sample-UISearchController

我希望这个例子可以解决你的问题。

答案 1 :(得分:0)

这是搜索控制器的惰性实例化:

    self.searchController = ({
        // Setup One: This setup present the results in the current view.
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.hidesNavigationBarDuringPresentation = false
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.searchBarStyle = .Minimal
        controller.searchBar.sizeToFit()
        self.tableView.tableHeaderView = controller.searchBar
        return controller
    })()

我希望有所帮助!