Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll UICollectionView to section header view

The code below scrolls to the right cell in UICollectionView, but the section header view is hidden behind UINavigationBar in my case. I believe I should use scrollRectToVisible instead and my question is, what is the right way to calculate the CGRect (y position) when the numberOfRows in a given section is variable.

- (void)scrollToPricing:(NSUInteger)row {      [self.collectionView scrollToItemAtIndexPath:       [NSIndexPath indexPathForItem:0                            inSection:row]                     atScrollPosition:UICollectionViewScrollPositionTop                             animated:YES]; } 
like image 973
Martin Koles Avatar asked Feb 28 '14 16:02

Martin Koles


2 Answers

Seems like all the answers are overly complex. This works for me:

let attributes = self.collectionView.collectionViewLayout.layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader, atIndexPath: NSIndexPath(forItem: 0, inSection: section))  self.collectionView.setContentOffset(CGPointMake(0, attributes!.frame.origin.y - self.collectionView.contentInset.top), animated: true) 

Swift 3:

if let attributes = collectionView.collectionViewLayout.layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: IndexPath(item: 0, section: section)) {     collectionView.setContentOffset(CGPoint(x: 0, y: attributes.frame.origin.y - collectionView.contentInset.top), animated: true) } 
like image 191
pixelfreak Avatar answered Oct 03 '22 01:10

pixelfreak


I think this may help you

UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath]; 

Then you can access the location through attributes.frame

like image 43
Sunny Shah Avatar answered Oct 03 '22 00:10

Sunny Shah