Ios – How to use UISearchDisplayController with UICollectionViewController

iosuicollectionviewuisearchbaruisearchdisplaycontrolleruitableview

If you use a UISearchDisplayController with a UITableViewController, when the user taps the search bar it animates up to replace the nav bar.

I'd like to get that same effect when using a UISearchBar at the top of a UICollectionViewController. Any ideas?

Best Answer

I had to add the searchBar programmatically as a subview of the UICollectionReusableView, I could never getting it working through IB as I kept getting prototype error when assigning an outlet. Adding the search bar in the implementation file worked for me.

The relevant methods are the following.

-(void)viewDidLoad
{
    [super viewDidLoad];
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CellIdentifier];
    _objectChanges = [NSMutableArray array];
    _sectionChanges = [NSMutableArray array];
    [self performFetch];
    searchBar = [[UISearchBar alloc]
                  initWithFrame:CGRectMake(0.0, 50.0, self.view.bounds.size.width,
                                           44.0)];
    searchBar.placeholder = @"Search for channels";
    searchBar.tintColor = [UIColor blackColor];
    searchBar.delegate = self;
}


-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    SupplementaryView *header = nil;

    if ([kind isEqual:UICollectionElementKindSectionHeader])
    {
        header = [self.collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                    withReuseIdentifier:@"reuseHeader"
                                                           forIndexPath:indexPath];

        [header addSubview:searchBar];

    }
    return header;
}