Display Items Side by side on iPad using UICollectionViewCompositionalLayout

47 Views Asked by At

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

enter image description here

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
}
1

There are 1 best solutions below

0
DonMag On

Looks like you are setting the itemSize wrong...

This line:

widthDimension: .fractionalWidth(0.2),

Tells the item to use 20% of the available width.

If you make this minor change:

let fw: CGFloat = (environment.container.contentSize.width > 500 && self.toggleSwitch.isOn) ? 0.5 : 1.0
let itemSize = NSCollectionLayoutSize (
    widthDimension: .fractionalWidth(fw), // .fractionalWidth(0.2),
    heightDimension: .estimated(400)
)
let item = NSCollectionLayoutItem(layoutSize: itemSize)

You should get your desired result.