I am using UICollectionView in my UIViewController.
My collectionview properties are set as below.
Now I would like cell to be Centre on screen after scroll! Option 1:
Option 2:
What would I have to do achieve option 2?
UPDATE:
In the end I have used following code as scrolling with other answer is not smooth.
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{ CGFloat offsetAdjustment = MAXFLOAT;
CGFloat horizontalCenter = proposedContentOffset.x + (CGRectGetWidth(self.collectionView.bounds) / 2.0);
CGRect targetRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
NSArray* array = [super layoutAttributesForElementsInRect:targetRect];
for (UICollectionViewLayoutAttributes* layoutAttributes in array) {
CGFloat itemHorizontalCenter = layoutAttributes.center.x;
if (ABS(itemHorizontalCenter - horizontalCenter) < ABS(offsetAdjustment)) {
offsetAdjustment = itemHorizontalCenter - horizontalCenter;
}
}
return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y);
}
I have found a lot of information and solutions.
now, I use this.
on UICollectionViewFlowLayout override:
and on UICollectionViewController:
now, cell is in center!!
preview
Here's a Swift 3 version of @dmitry-zhukov (thanks btw!)
You can override
targetContentOffsetForProposedContentOffset:withScrollingVelocity:
method in yourUICollectionViewLayout
subclass and calculate your offset there like this:EDIT: thanks for pointing this out, forgot to say that you have to disable paging first:
UPDATE: attaching Swift 4.2 version
I don't know why everybody's answer is so complicated, I simply turn on
Paging enabled
in Interface Builder and it works perfectly.you can use code
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)