Using a UICollectionViewController
I am attempting to create a section header that is sticky, by that I mean on scroll up it is fixed in position, with my UICollectionViewCell
's scrolling beneath it.
I would then like, on scroll down, to have the header stick in position, but stretch as the user pulls.
I can achieve both this individually but have been unable to combine these effects.
StickyHeader
fileprivate func configureCollectionViewLayout() {
if let layout = collectionViewLayout as? UICollectionViewFlowLayout {
let padding: CGFloat = 16
layout.sectionInset = .init(top: padding, left: padding, bottom: padding, right: padding)
layout.sectionHeadersPinToVisibleBounds = true
}
}
StretchyHeader
class StretchyHeaderLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let layoutAttributes = super.layoutAttributesForElements(in: rect)
layoutAttributes?.forEach({ (attributes) in
if attributes.representedElementKind == UICollectionView.elementKindSectionHeader && attributes.indexPath.section == 0 {
guard let collectionView = collectionView else { return }
let contentOffsetY = collectionView.contentOffset.y
if contentOffsetY > 0 { return }
let width = collectionView.frame.width
let height = attributes.frame.height - contentOffsetY
attributes.frame = CGRect(x: 0, y: contentOffsetY, width: width, height: height)
}
})
return layoutAttributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
Using the StretchyHeaderLayout
I create my UICollectionViewController
as FeedController(collectionViewLayout: StretchyHeaderLayout())
I then set a custom header view using
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath)
return header
}
My header view is simply view that consumes a few extensions to provide a UIImage based on a colour hex and also anchor that image on all 4 corners
class PageHeaderView: UICollectionReusableView {
let headerBgView: UIImageView = {
let iv = UIImageView(image: UIImage.from(hex: "ffffff"))
return iv
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(headerBgView)
headerBgView.fillSuperview()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Please let me know if these extensions would aid your input.