I set up a collection view and its layout with the new compositional stuff and it has been pretty cool, it seems to be very expandable but I can't find a way to make items centered in the collection, which is IMO a basic feature that one would imagine being supported..
What I have is:
Accomplished with this code:
UICollectionViewCompositionalLayout { section, env in
let tagDefaultSize = CGSize(width: 100, height: 40)
let item = NSCollectionLayoutItem(
layoutSize: NSCollectionLayoutSize(widthDimension: .estimated(tagDefaultSize.width), heightDimension: .absolute(tagDefaultSize.height))
)
item.edgeSpacing = NSCollectionLayoutEdgeSpacing(
leading: .fixed(0),
top: .fixed(0),
trailing: .fixed(8),
bottom: .fixed(0)
)
let group = NSCollectionLayoutGroup.horizontal(
layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(tagDefaultSize.height)),
subitems: [item]
)
group.edgeSpacing = NSCollectionLayoutEdgeSpacing(
leading: .flexible(8),
top: .fixed(0),
trailing: .fixed(8),
bottom: .fixed(8)
)
let section = NSCollectionLayoutSection(group: group)
section.contentInsets = NSDirectionalEdgeInsets(
top: 30,
leading: 20,
bottom: 40,
trailing: 20
)
return section
}
But what I need is this:
Has anyone had any luck with this? Thanks
I found a solution for this, using
I created the following extension, which calculates the frames of each element in the group, centring as many items as will fit on each row
Then create a layout section with a single group that contains all the items in that section. First you'll first need to calculate the sizes of all the elements in the section, and then pass those in to the function above, something like this (note that I'm using a DiffableDataSource here)…
and then create the layout…