Scroll to UICollectionView header
Scroll to UICollectionView header in Swift
Introduction
One of the things that the UICollectionView lacks is the UITableView’s index title capability. You have to roll your own with the UICollectionView. I’ll leave that UI frob to you, but this quick post will show you how to scroll to show a section header.
How to
Here is the first cut at scrolling to the second section (section 1). The problem is, it scrolls to the first item and the header is not shown. If that’s what you want, you can stop reading.
1 2 3 4 |
if let cv = self.collectionView { cv.scrollToItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 1), atScrollPosition: .Top, animated: true) } |
As usual, the “answers” at StackOverflow are mostly in the weeds. I don’t want to get locations directly from the layout delegate for example.
What you want to do is to ask the collection view for the layout attributes for your header view.
You can do this with a single function call:
1 2 |
if let attributes = cv.layoutAttributesForSupplementaryElementOfKind(UICollectionElementKindSectionHeader, atIndexPath: indexPath) { |
You can then use the attribute.frame property to determine the header’s location. With that in hand, you can call setContentOffset() to scroll.
Summary
Don’t mess around with doing the math yourself. Ask the collection view for the header’s attributes and use that frame to scroll.
Here is a Gist.
Hi,
Awesome tutorial about the CollectionView header scrolling! When I try to add your example, my CollectionView adds another header. How can I resolve this?
Kind Regards,
Tim
it helped me. thanks for the sort tutorial, i’ve used
let cv_attribute = collectionView.layoutAttributesForSupplementaryElement(ofKind: UICollectionElementKindSectionHeader, at: IndexPath.init(item: 0, section: 0))
collectionView.scrollRectToVisible((cv_attribute?.frame)!, animated: true)