Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios UICollectionView remove header programmatically

I want have a control of the header of a UICollectionView as I need to remove and add it based on user-generated events.

What I have tried so far:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{

    if(toRemoveHeader){

        return CGSizeZero;

    }else{

        return CGSizeMake(320, 45);

    }
}

And then call [self.collectionView reloadData] whenever the user-event is generated. I would prefer to make this without reloading the data. Any ideas?

like image 896
Petar Avatar asked Mar 14 '14 09:03

Petar


2 Answers

If you are using Swift you can do it this way in your UICollectionViewController subclass:

var hideHeader: Bool = true //or false to not hide the header

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    if hideHeader {
        return CGSizeZero //supplementary view will not be displayed if height/width are 0
    } else {
        return CGSizeMake(30,80) //size of your UICollectionReusableView
    }
}
like image 119
gammachill Avatar answered Oct 14 '22 15:10

gammachill


Your implementation is fully functional, the problem might be that you don't assign the object implementing that function to the delegate property of your collectionView.

The function collectionView:layout:referenceSizeForHeaderInSection: is implemented by a class confirming to the UICollectionViewDelegateFlowLayout protocol, and the collectionView expects its delegate to implement this method, and not its dataSource.

In one of my implementations I show a footer only if there are no cells in that section, and as long as the delegate property is set correctly it works perfectly.

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize) collectionView:(UICollectionView *)collectionView
                   layout:(UICollectionViewLayout *)collectionViewLayout
referenceSizeForFooterInSection:(NSInteger)section
{
    NSUInteger count = [self collectionView: collectionView
                     numberOfItemsInSection: section];
    CGFloat footerHeight = (count == 0) ? 60.f : 0.f;
    CGFloat footerWidth = collectionView.frame.size.width;
    return CGSizeMake(footerWidth, footerHeight);
}
like image 32
Aerows Avatar answered Oct 14 '22 14:10

Aerows