Ios – Can’t use UISearchController with UICollectionView

iosuicollectionviewuisearchbar

In the WWDC 2014 talk " A Look Inside Presentation Controllers" the presenters showed how to setup a UISearchController in a UITableView. They do this by setting the searchController's searchBar's frame, then setting it as the tableView's tableHeaderView. Unfortunately, there isn't an equivalent of tableHeaderView for UICollectionView. With UISearchDisplayController, this would be simple: create a UISearchBar and add it to a custom UICollectionView section header, then initialize the UISearchDisplayController with the search bar. The problem is, you can't initialize a UISearchController with a UISearchBar, or even set the searchBar because it's a read-only property. I guess my real question is, what are my options? Is there a "good" way to implement search without UISearchDisplayController or UISearchController?

Best Answer

With UISearchDisplayController, this would be simple: create a UISearchBar and add it to a custom UICollectionView section header, then initialize the UISearchDisplayController with the search bar

The search bar in a UISearchController is created for you. When you are asked the supplementary view in the data source method

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath

add the searchController.searchBar as a subview of the supplementary view. Don't forget to call

[searchController.searchBar sizeToFit]

in order to give the search bar the appropriate size.

Related Topic