Question

I have added an UISearchBar to the header of a CollectionView. I want to show the UISearchBar only if the user wants to see it. I want to hide it behind the NavigationBar, just like Whats App does.

I have used an UICollectionReusableView to add the SearchBar.

Was it helpful?

Solution

UICollectionView is a subclass of UIScrollView, so you need to set the delegate for your collection view and implement the scroll view delegate methods like below.

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    CGFloat contentOffset = scrollView.contentOffset.y;

    // If the header is already shown, it will be hidden right when you start scrolling down
    if (contentOffset >= 0) {
        if (self.showHeader) {
                [UIView animateWithDuration:.5 animations:^{
                    self.collectionView.frame = CGRectMake(0, -HEADER_HEIGHT, 320, COLLECTION_VIEW_HEIGHT+HEADER_HEIGHT);
                } completion:^(BOOL finished) {
                }];
                self.showHeader = NO;
            }
    }
}

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    CGFloat contentOffset = scrollView.contentOffset.y;

    // When you scroll up to the point that the header can be seen, reveal it
    // Adjust the offset limit to suit your need
    if (contentOffset < -HEADER_HEIGHT+10) {
        if (!self.showHeader) {
                self.collectionView.frame = CGRectMake(0, 0, 320, COLLECTION_VIEW_HEIGHT);
                self.showHeader = YES;
            }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top