Skip to content

Instantly share code, notes, and snippets.

@genedelisa
Last active November 22, 2023 22:22
Show Gist options
  • Save genedelisa/ebcc33c38a521ff8a719 to your computer and use it in GitHub Desktop.
Save genedelisa/ebcc33c38a521ff8a719 to your computer and use it in GitHub Desktop.
UICollectionView scroll to make section header visible
/**
Scroll to make the the given section header visible.
The function scrollToItemAtIndexPath will scroll to the item and hide the section header.
Swift 3.
*/
func scrollToSection(_ section:Int) {
if let cv = self.collectionView {
let indexPath = IndexPath(item: 1, section: section)
if let attributes = cv.layoutAttributesForSupplementaryElement(ofKind: UICollectionElementKindSectionHeader, at: indexPath) {
let topOfHeader = CGPoint(x: 0, y: attributes.frame.origin.y - cv.contentInset.top)
cv.setContentOffset(topOfHeader, animated:true)
}
}
}
@Madhivanan
Copy link

This functionality not working.

@genedelisa
Copy link
Author

I just tried it again and it works.

@douglastaquary
Copy link

douglastaquary commented Feb 23, 2017

Two questions: where do i call this method ? In

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView 

And, If i have several sections? 


Something like that not work :/ 

```swift 
func scrollToSection(_ section:Int)  {
let numberOfItems =  sections[section].items.count
       if let cv = self.collectionView {
                       let indexPath = numberOfItems.map { IndexPath.init(item: $0, section: section)}
           if let attributes =  cv.layoutAttributesForSupplementaryElement(ofKind: UICollectionElementKindSectionHeader, at: indexPath) {
               
               let topOfHeader = CGPoint(x: 0, y: attributes.frame.origin.y - cv.contentInset.top)
               cv.setContentOffset(topOfHeader, animated:true)
           }
       }
   }

@mchinnu
Copy link

mchinnu commented Apr 27, 2017

Its working, cool and simple, Thanks!

@DoctorFinlay
Copy link

Love this - it saved me a lot of time! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment