My intention is to display the items side by side on iPad and line by line in iPhone. My code as bellow but for some reason Im getting the layout wrong. Any help would be much appreciate.
What I get is this cramped up UI
But what I get is shrink layout. My code as bellow
//Configure the layout of the elements based on the device size
private func layout() -> UICollectionViewCompositionalLayout {
let layout = UICollectionViewCompositionalLayout { [weak self] sectionIndex, environment -> NSCollectionLayoutSection? in
guard let self = self else { return nil }
let itemSize = NSCollectionLayoutSize (
widthDimension: .fractionalWidth(0.2),
heightDimension: .estimated(400)
)
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize (
widthDimension: .fractionalWidth(1.0),
heightDimension: .estimated(400)
)
//Not only on iPad but also this works on phone's landscape in this way
let columns = (environment.container.contentSize.width > 500 && self.toggleSwitch.isOn) ? 2 : 1
//Issue is here
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, repeatingSubitem: item, count: columns)
group.interItemSpacing = .fixed(20)
if columns > 1 {
group.contentInsets.leading = 20
group.contentInsets.trailing = 20
}
let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = 20
section.contentInsets.top = 20
return section
}
let config = UICollectionViewCompositionalLayoutConfiguration()
config.interSectionSpacing = 50
layout.configuration = config
return layout
}

Looks like you are setting the
itemSizewrong...This line:
Tells the item to use 20% of the available width.
If you make this minor change:
You should get your desired result.