Search code examples
iosobjective-cuicollectionviewnsindexpathuicollectionreusableview

How to detect scrolling to a new section in a UICollectionView?


I am implementing an infinite-scrolling calendar. My issue is that I would like to set the current month as the title in the navigation bar and it should update while scrolling - once you pass the section header view the title should update in the nav bar.

A possible solution would be to set the view title in the method called - (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath so that, when I calculate a new section Header, it also updates the title. The problem with this is that the title changes when the new section is at the bottom of the page.

Currently displaying the Section Header as title, not optimal

Is there a way to know the "current section" of UICollectionView once the user has scrolled to it? Or can you think of a way to improve my current solution?

To help the readers of this post, I posted my own sample code for this question at this GitHub repo.


Solution

  • change below line in method viewForSupplementaryElementOfKind :

    self.title = [df stringFromDate:[self dateForFirstDayInSection:indexPath.section]];
    

    to this:

        if(![[self dateForFirstDayInSection:indexPath.section-1] isKindOfClass:[NSNull class]]){
            self.title = [df stringFromDate:[self dateForFirstDayInSection:indexPath.section-1]];
    }
    

    Hope it will help you.