UICollectionView scrolls to any footer or header

I want to scroll to the footer or header of the collection view, however the standard approach with scrollToItemAtIndexPath scrolls only to cells

 - (void)scrollToBottom { NSInteger section = [self numberOfSectionsInCollectionView:self.collectionView] - 1; NSInteger item = [self collectionView:self.collectionView numberOfItemsInSection:section] - 1; if ((section > 0) && (item > 0)) { NSIndexPath * lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section]; [self.collectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:NO]; } } 

How to scroll any footer, a header similar to scrolling to a cell?

+6
source share
2 answers

I know this is an old question, but I recently had the same issue. The best solution I found was from Gene De Lisa at http://www.rockhoppertech.com/blog/scroll-to-uicollectionview-header/ As you seem to be working in Obj-C, here is the port of its Swift code, which i use:

 -(void) scrollToSectionHeader:(int)section { NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:section]; UICollectionViewLayoutAttributes *attribs = [self.collectionView layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath]; CGPoint topOfHeader = CGPointMake(0, attribs.frame.origin.y - self.collectionView.contentInset.top); [self.collectionView setContentOffset:topOfHeader animated:YES]; } 

The code above will scroll correctly to the title of this section (all I need). Trivially changing this to go to the footer instead:

 -(void) scrollToSectionFooter:(int)section { NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:section]; UICollectionViewLayoutAttributes *attribs = [self.collectionView layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionFooter atIndexPath:indexPath]; CGPoint topOfFooter = CGPointMake(0, attribs.frame.origin.y - self.collectionView.contentInset.top); [self.collectionView setContentOffset:topOfFooter animated:YES]; } 
+6
source

An old question, but still relevant, as it seems. For me - @mojoTosh's solution did not work, but there was the following: (Swift 4)

  if let attributes = self.collectionView?.layoutAttributesForSupplementaryElement(ofKind: UICollectionElementKindSectionHeader, at: indexPath), let cellAttributes = self.collectionView?.layoutAttributesForItem(at: indexPath) { let scrollingPosition = CGPoint(x: 0.0, y: cellAttributes.frame.origin.y - attributes.frame.size.height - collectionView.contentInset.top) self.collectionView?.setContentOffset(scrollingPosition, animated: true) 
0
source

Source: https://habr.com/ru/post/973534/


All Articles