I have a horizontal scrolling collectionView with each cell the size of the view. When I page through the collectionView it doesn\'t page by cell. The cells aren\'t in the c
If you're after the behaviour of collectionView.isPagingEnabled
(so with 'proper inertia feeling' etc) but without wrong offsets when setting a contentInset or spacing, this is what you need:
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) {
let itemWidth = cellSize.width + spacing
let inertialTargetX = targetContentOffset.pointee.x
let offsetFromPreviousPage = (inertialTargetX + collectionView.contentInset.left).truncatingRemainder(dividingBy: itemWidth)
// snap to the nearest page
let pagedX: CGFloat
if offsetFromPreviousPage > itemWidth / 2 {
pagedX = inertialTargetX + (itemWidth - offsetFromPreviousPage)
} else {
pagedX = inertialTargetX - offsetFromPreviousPage
}
let point = CGPoint(x: pagedX, y: targetContentOffset.pointee.y)
targetContentOffset.pointee = point
}