Skip to content

Instantly share code, notes, and snippets.

@comiclandapp
Forked from ilyapuchka/StickyLayout.swift
Created May 10, 2022 00:27
Show Gist options
  • Save comiclandapp/32992de669a3698b4f49edb270964ad7 to your computer and use it in GitHub Desktop.
Save comiclandapp/32992de669a3698b4f49edb270964ad7 to your computer and use it in GitHub Desktop.
Really sticky collection view layout
// The issue with sectionHeadersPinToVisibleBounds and sectionFootersPinToVisibleBounds is that they do not pin
// first header and last footer when bouncing. This layout subclass fixes that.
class StickyLayout: UICollectionViewFlowLayout {
override init() {
super.init()
self.sectionFootersPinToVisibleBounds = true
self.sectionHeadersPinToVisibleBounds = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.sectionFootersPinToVisibleBounds = true
self.sectionHeadersPinToVisibleBounds = true
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributes = super.layoutAttributesForElements(in: rect) else { return nil }
for attribute in attributes {
adjustAttributesIfNeeded(attribute)
}
return attributes
}
override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let attributes = super.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath) else { return nil }
adjustAttributesIfNeeded(attributes)
return attributes
}
func adjustAttributesIfNeeded(_ attributes: UICollectionViewLayoutAttributes) {
switch attributes.representedElementKind {
case UICollectionElementKindSectionHeader?:
adjustHeaderAttributesIfNeeded(attributes)
case UICollectionElementKindSectionFooter?:
adjustFooterAttributesIfNeeded(attributes)
default:
break
}
}
private func adjustHeaderAttributesIfNeeded(_ attributes: UICollectionViewLayoutAttributes) {
guard let collectionView = collectionView else { return }
guard attributes.indexPath.section == 0 else { return }
if collectionView.contentOffset.y < 0 {
attributes.frame.origin.y = collectionView.contentOffset.y
}
}
private func adjustFooterAttributesIfNeeded(_ attributes: UICollectionViewLayoutAttributes) {
guard let collectionView = collectionView else { return }
guard attributes.indexPath.section == collectionView.numberOfSections - 1 else { return }
if collectionView.contentOffset.y + collectionView.bounds.size.height > collectionView.contentSize.height {
attributes.frame.origin.y = collectionView.contentOffset.y + collectionView.bounds.size.height - attributes.frame.size.height
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment