Skip to content

Instantly share code, notes, and snippets.

@fuxingloh
Last active January 14, 2020 14:00
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 fuxingloh/80f3ff4161f44a6130fdac7e4bf0bbda to your computer and use it in GitHub Desktop.
Save fuxingloh/80f3ff4161f44a6130fdac7e4bf0bbda to your computer and use it in GitHub Desktop.
UI collection view flow layout snapping.
//
// Created by Fuxing Loh on 2019-03-07.
// Copyright (c) 2019 Munch Technologies. All rights reserved.
//
import Foundation
import UIKit
class UICollectionViewFlowLayoutSnapping: UICollectionViewFlowLayout {
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
// Page width used for estimating and calculating paging.
let pageWidth = self.itemSize.width + minimumLineSpacing
// Make an estimation of the current page position.
let approximatePage = self.collectionView!.contentOffset.x/pageWidth
// Determine the current page based on velocity.
let currentPage = (velocity.x < 0.0) ? floor(approximatePage) : ceil(approximatePage)
// Create custom flickVelocity.
let flickVelocity = velocity.x * 0.3
// Check how many pages the user flicked, if <= 1 then flickedPages should return 0.
let flickedPages = (abs(round(flickVelocity)) <= 1) ? 0 : round(flickVelocity)
// Calculate newHorizontalOffset.
let newHorizontalOffset = ((currentPage + flickedPages) * pageWidth) - self.collectionView!.contentInset.left
return CGPoint(x: newHorizontalOffset, y: proposedContentOffset.y)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment