Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mstubna/beed10327e00310d05f12bf4747266a4 to your computer and use it in GitHub Desktop.
Save mstubna/beed10327e00310d05f12bf4747266a4 to your computer and use it in GitHub Desktop.
import UIKit
class SleepLogCollectionViewFlowLayout: UICollectionViewFlowLayout {
override func targetContentOffset(
forProposedContentOffset proposedContentOffset: CGPoint,
withScrollingVelocity velocity: CGPoint
) -> CGPoint {
var _proposedContentOffset = CGPoint(
x: proposedContentOffset.x, y: proposedContentOffset.y
)
var offSetAdjustment: CGFloat = CGFloat.greatestFiniteMagnitude
let horizontalCenter: CGFloat = CGFloat(
proposedContentOffset.x + (self.collectionView!.bounds.size.width / 2.0)
)
let targetRect = CGRect(
x: proposedContentOffset.x,
y: 0.0,
width: self.collectionView!.bounds.size.width,
height: self.collectionView!.bounds.size.height
)
let array: [UICollectionViewLayoutAttributes] =
self.layoutAttributesForElements(in: targetRect)!
as [UICollectionViewLayoutAttributes]
for layoutAttributes: UICollectionViewLayoutAttributes in array {
if layoutAttributes.representedElementCategory == UICollectionElementCategory.cell {
let itemHorizontalCenter: CGFloat = layoutAttributes.center.x
if abs(itemHorizontalCenter - horizontalCenter) < abs(offSetAdjustment) {
offSetAdjustment = itemHorizontalCenter - horizontalCenter
}
}
}
var nextOffset: CGFloat = proposedContentOffset.x + offSetAdjustment
repeat {
_proposedContentOffset.x = nextOffset
let deltaX = proposedContentOffset.x - self.collectionView!.contentOffset.x
let velX = velocity.x
if
deltaX == 0.0 || velX == 0 || (velX > 0.0 && deltaX > 0.0) ||
(velX < 0.0 && deltaX < 0.0)
{
break
}
if velocity.x > 0.0 {
nextOffset = nextOffset + self.snapStep()
} else if velocity.x < 0.0 {
nextOffset = nextOffset - self.snapStep()
}
} while self.isValidOffset(offset: nextOffset)
_proposedContentOffset.y = 0.0
return _proposedContentOffset
}
func isValidOffset(offset: CGFloat) -> Bool {
return (offset >= CGFloat(self.minContentOffset()) &&
offset <= CGFloat(self.maxContentOffset()))
}
func minContentOffset() -> CGFloat {
return -CGFloat(self.collectionView!.contentInset.left)
}
func maxContentOffset() -> CGFloat {
return CGFloat(
self.minContentOffset() + self.collectionView!.contentSize.width - self.itemSize.width
)
}
func snapStep() -> CGFloat {
return self.itemSize.width + self.minimumLineSpacing
}
}
@mstubna
Copy link
Author

mstubna commented Sep 26, 2016

Updated for Swift 3

@29satnam
Copy link

Still saving lives!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment