I have a UICollectionView
and it has quite a lot of UICollectionViewCells
on it. I want to scroll the cell to the centre of the UICollectionView
when it is tapped. My concern is that even if I tap the last or the top cell it should move to the centre of the collection view.
I have tried setting the contentInsets
and offsets but they don't seem to work. I think I will have to change the content size on selection and change it back to original when the scrolling begins.
Swift 3 solution for scrolling and centering screen to make the tapped item visible:
This doesn't add inset above or under the
collectionView
!It seems that this bug is caused by a bad interaction between the scroll view's
contentInset
andUICollectionViewFlowLayout
. In my testing, settinglayout.sectionInset
rather thancollectionView.contentInset
eliminated the problem.Based on the accepted answer above, I would eliminate the workaround, and change:
to
You can use
scrollToItemAtIndexPath
method to put selected(tapped) cell to center position in UICollectionViewYou can use
UICollectionViewScrollPositionCenteredVertically
for vertical centered positionSetting contentInsets should give some extra space around first and last cells:
After you should call:
It's important to pass correct scroll position: UICollectionViewScrollPositionCenteredVertically
This should center tapped item properly.
EDIT
It's really strange, but after setting UIEdgeInsets to collection view method scrollToItemAtIndexPath does not works properly, so i make some modification:
it works fine for me.