UICollectionViewCompositionalLayout with groupPagingCentered doesn't start centered
Maybe too late, but here is a workaround:
func createLayout() -> UICollectionViewLayout {
let layout = UICollectionViewCompositionalLayout { (sectionIndex, environment) -> NSCollectionLayoutSection? in
let sideInset: CGFloat = 5
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
item.contentInsets = .init(top: 0, leading: sideInset, bottom: 0, trailing: sideInset)
let groupWidth = environment.container.contentSize.width * 0.93
let groupSize = NSCollectionLayoutSize(widthDimension: .absolute(groupWidth), heightDimension: .fractionalHeight(1.0))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
// add leading and trailing insets to the section so groups are aligned to the center
let sectionSideInset = (environment.container.contentSize.width - groupWidth) / 2
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: sectionSideInset, bottom: 0, trailing: sectionSideInset)
// note this is not .groupPagingCentered
section.orthogonalScrollingBehavior = .groupPaging
return section
}
return layout
}
This is expected behavior. "centered" means a cell snaps to the center after scrolling. Before doing any scrolling, the whole group is scrolled all the way to the right. Your group is only 0.93
fractional width so the difference is slight. The effect is much less unsightly when the fractional width is smaller.