Reputation: 476
I have a problem with a horizontal scroll in collectionView
.
I want to scroll by section. I have 3 sections. I want to center it in the view.
First, it looks how I want
But when I scroll next... Left and right insets are different.
The last one is broken too.
I tried it with function scrollViewDidEndDecelerating
, but it didn't work. Animation of it was ugly.
My code of collectionView
layout.
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 15)
layout.minimumLineSpacing = 5
layout.scrollDirection = .horizontal
Upvotes: 0
Views: 2161
Reputation: 473
You have to implement UICollectionViewDelegateFlowLayout
methods to solve this problem.
let minLineSpace = 4
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width - minLineSpace, height: collectionView.frame.size.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return minLineSpace
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, (minLineSpace / 2), 0, (minLineSpace / 2))
}
Here I have added 4 point spacing between two cells, you can customise this as per your requirement.
Upvotes: 2