Skip to content

Instantly share code, notes, and snippets.

@Sjahriyar
Created December 19, 2019 14:57
Show Gist options
  • Save Sjahriyar/ab81078d93b071c1775aa5f0bdac9ef9 to your computer and use it in GitHub Desktop.
Save Sjahriyar/ab81078d93b071c1775aa5f0bdac9ef9 to your computer and use it in GitHub Desktop.
CollectionView Snap to the next cell
//
// TransactionsCollectionViewFlowLayout.swift
//
// Created by Shahriyar Soheilizadeh on 19/12/2019.
// Copyright © 2019 Shahriyar Soheilizadeh. All rights reserved.
//
import UIKit
class TransactionsCollectionViewFlowLayout: UICollectionViewFlowLayout
{
override func prepare() {
super.prepare()
scrollDirection = .horizontal
}
override public func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
guard let collectionView = collectionView else {
return super.targetContentOffset(forProposedContentOffset: proposedContentOffset, withScrollingVelocity: velocity)
}
var offsetAdjustment = CGFloat.greatestFiniteMagnitude
// If you don't have minimumLineSpacing, remove it at the end of this line.
let horizontalOffset = proposedContentOffset.x + collectionView.contentInset.left + minimumLineSpacing
let targetRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
let layoutAttributesArray = super.layoutAttributesForElements(in: targetRect)
layoutAttributesArray?.forEach({ (layoutAttributes) in
let itemOffset = layoutAttributes.frame.origin.x
if fabsf(Float(itemOffset - horizontalOffset)) < fabsf(Float(offsetAdjustment)) {
offsetAdjustment = itemOffset - horizontalOffset
}
})
return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment