Programmatically scroll to a supplementary view within UICollectionView

后端 未结 4 1692
没有蜡笔的小新
没有蜡笔的小新 2021-02-07 02:05

I am using UICollectionView to display photos in sections. Each section has a supplementary view as a header and is supplied via the method: viewForSupplement

4条回答
  •  礼貌的吻别
    2021-02-07 02:08

    One thing the solutions don't manage is if you are pinning section headers. The methods work fine with unpinned headers, but if your headers are pinned, while scrolling to a section above the current section, it will stop once the section header appears (which will be for the bottom row of your section). That may be desirable in some cases but I think the goal is to put the top of the section at the top of the screen.

    In which case you need to take the methods above and adjust them a bit. For instance:

    UICollectionView *cv = self.collectionView;
    CGFloat contentInsetY = cv.contentInset.top;
    CGFloat offsetY = [cv layoutAttributesForItemAtIndexPath:ip].frame.origin.y;
    CGFloat sectionHeight =
    [cv layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:ip].frame.size.height;
    [cv setContentOffset:CGPointMake(cv.contentOffset.x, offsetY - contentInsetY - sectionHeight) animated:YES];
    

    Now you are basically scrolling the first row of your section to visible, less the height of its section header. This will put the section header on the top where you want it with pinned headers so the direction of the scroll won't matter anymore. I didn't test with section insets.

提交回复
热议问题