I have a requirement to keep UICollectionViewCell center aligned in portrait mode.
Final result should be like :
animation
I'm using this code to do this:
override public func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
var layoutAttributes: Array = layoutAttributesForElements(in: collectionView!.bounds)!
if layoutAttributes.count == 0 {
return proposedContentOffset
}
var firstAttribute: UICollectionViewLayoutAttributes = layoutAttributes[0]
for attribute: UICollectionViewLayoutAttributes in layoutAttributes {
if attribute.representedElementCategory != .cell {
continue
}
if((velocity.x >= 0.0 && attribute.center.x > firstAttribute.center.x) ||
(velocity.x <= 0.0 && attribute.center.x < firstAttribute.center.x)) {
firstAttribute = attribute;
}
}
return CGPoint(x: firstAttribute.center.x -
collectionView!.bounds.size.width * 0.5, y: proposedContentOffset.y)
}
This works fine for all cell except the last cell which doesn't get center aligned upon scrolling.
Actual result:

Is there any way to resolve this issue?
I found that if I set
collectionView.isPagingEnabled = true
it will broken the center cell setting. Once I turn it off, everything works fine again
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With