Skip to content

Instantly share code, notes, and snippets.

@siilver777
Last active March 2, 2019 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siilver777/0a8a38aac5005c3d7dec3c56aa172243 to your computer and use it in GitHub Desktop.
Save siilver777/0a8a38aac5005c3d7dec3c56aa172243 to your computer and use it in GitHub Desktop.
Make a stretchy & blurry collection header
class Layout: UICollectionViewFlowLayout {
// Recompute layout on scroll
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
// Update header size based on content offset (and keep it at the top)
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let layoutAttributes = super.layoutAttributes(in: rect)
layoutAttributes?.forEach {
if $0.representedElementKind == UICollectionView.elementKindSectionHeader && $0.indexPath.section == 0 {
guard let collectionView = collectionView else { return }
let contentOffsetY = collectionView.contentOffset.y
// Update header only when scrolling from top to bottom
guard contentOffset <= 0 else { return }
let width = collectionView.frame.width
let height = $0.frame.height - contentOffsetY
$0.frame = CGRect(x: 0, y: contentOffsetY, width: width, height: height)
}
}
return layoutAttributes
}
}
class HeaderView: UICollectionReusableView {
var animator: UIViewPropertyAnimator?
func setupBlur() {
animator = UIViewPropertyAnimator(duration: 3.0, curve: .linear) { [weak self] in
let blurEffect = UIBlurEffect(style: .regular)
let visualEffectView = UIVisualEffectView(effect: blurEffect)
self?.addSubview(visualEffectView)
// Don't forget the constraints
}
}
}
class CollectionViewController: UICollectionViewController {
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let contentOffsetY = scrollView.contentOffset.y
// Remove blur when scrolling from bottom to top
if contentOffsetY > 0 {
headerView?.animator?.fractionComplete = 0
return
}
// Displays the blur accordingly
headerView?.animator?.fractionComplete = abs(contentOffsetY) / 100
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment