Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"targetContentOffset" UICollectionViewFlowLayout not working properly

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:

enter image description here

Is there any way to resolve this issue?

like image 214
Arun_ Avatar asked Dec 10 '25 17:12

Arun_


1 Answers

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

like image 141
mmk Avatar answered Dec 13 '25 05:12

mmk