Programmatically scroll to a supplementary view within UICollectionView

后端 未结 4 1696
没有蜡笔的小新
没有蜡笔的小新 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:18

    // scroll to selected index
    NSIndexPath* cellIndexPath = [NSIndexPath indexPathForItem:0 inSection:sectionIndex];
    UICollectionViewLayoutAttributes* attr = [self.collectionView.collectionViewLayout layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:cellIndexPath];
    UIEdgeInsets insets = self.collectionView.scrollIndicatorInsets;
    
    CGRect rect = attr.frame;
    rect.size = self.collectionView.frame.size;
    rect.size.height -= insets.top + insets.bottom;
    CGFloat offset = (rect.origin.y + rect.size.height) - self.collectionView.contentSize.height;
    if ( offset > 0.0 ) rect = CGRectOffset(rect, 0, -offset);
    
    [self.collectionView scrollRectToVisible:rect animated:YES];
    

提交回复
热议问题