How to reload only data section of UICollectionVie

2019-03-21 07:07发布

问题:

I'm trying to reload only data section, not header or footer (supplementary view), of UICollectionView.

When I use reloadData method, header and footer section also reloads, so that's what I want.

I found the method reloadSections:, but I don't know why it doesn't work.

Because my collection view only contains one section, so I tried using the method like this:

[collectionViewController.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];

But it makes runtime error when the method is called. The content of error is:

'NSInvalidArgumentException', reason: '-[UICollectionViewUpdateItem action]:
unrecognized selector sent to instance 0x90aec00'

Is the method reloadSections: is not allowed to use like this? Is there any alternative way to reload only data section, not header or footer section?

回答1:

I think the error only occurs when the search bar is a collection view's subview, and trying to call reloadSections: when the keyboard input is up.

This article gives an answer to a similar problem, but that didn't work for me.

So I used an alternative way with which I can invoke almost the same feature.

Instead of adding the header as a supplementary view, I made the header a subview of 'view'. (not collectionView)

And added some scroll delegate to mimic the table view's header.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y = scrollView.contentOffset.y;
    if (y < 44) {
        [self.searchBar setFrame:CGRectMake(0, -y, 320, 44)];
        [self.searchBar setHidden:NO];
    } else if (y >= 44) {
        [self.searchBar setHidden:YES];
    }  
}