Skip to content

Instantly share code, notes, and snippets.

@MaherKSantina
Created July 24, 2018 08:28
Show Gist options
  • Save MaherKSantina/a9da40b01333440a48f0ad3ec12f7e2a to your computer and use it in GitHub Desktop.
Save MaherKSantina/a9da40b01333440a48f0ad3ec12f7e2a to your computer and use it in GitHub Desktop.
MSPCVDI Snippet 5
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let target = targetContentOffset.pointee
//Current scroll distance is the distance between where the user tapped and the destination for the scrolling (If the velocity is high, this might be of big magnitude)
let currentScrollDistance = target.x - currentScrollOffset.x
//Make the value an integer between -1 and 1 (Because we don't want to scroll more than one item at a time)
let coefficent = Int(max(-1, min(currentScrollDistance/scrollThreshold, 1)))
let currentIndex = Int(round(currentScrollOffset.x/itemWidth))
let adjacentItemIndex = currentIndex + coefficent
let adjacentItemIndexFloat = CGFloat(adjacentItemIndex)
let adjacentItemOffsetX = adjacentItemIndexFloat * (itemWidth(scrollView) + cellSpacing)
targetContentOffset.pointee = CGPoint(x: adjacentItemOffsetX, y: target.y)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment