Last active
April 17, 2017 03:38
-
-
Save katopz/8b04c783387f0c345cd9 to your computer and use it in GitHub Desktop.
Custom UICollectionViewFlowLayout refer to http://stackoverflow.com/questions/13492037/targetcontentoffsetforproposedcontentoffsetwithscrollingvelocity-without-subcla?nah=1#28813308
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class EMCollectionViewFlowLayout: UICollectionViewFlowLayout { | |
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { | |
var _proposedContentOffset = CGPoint(x: proposedContentOffset.x, y: proposedContentOffset.y) | |
var offSetAdjustment: CGFloat = CGFloat.max | |
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) | |
var array: [UICollectionViewLayoutAttributes] = self.layoutAttributesForElementsInRect(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 | |
do { | |
_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(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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment