使用 UICollectionViewCompositionalLayout 在 iPad 上并排显示项目

问题描述 投票:0回答:1

我的目的是在 iPad 上并排显示项目,在 iPhone 上逐行显示项目。我的代码如下,但由于某种原因我的布局错误。任何帮助将不胜感激。

我得到的是这个狭窄的用户界面

但我得到的是收缩布局。我的代码如下

//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
}
ios swift uicollectionview uicollectionviewcompositionallayout
1个回答
0
投票

看起来您设置的

itemSize
错误...

这一行:

widthDimension: .fractionalWidth(0.2),

告诉项目使用可用宽度的 20%。

如果您进行此微小更改:

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)

您应该会得到您想要的结果。

© www.soinside.com 2019 - 2024. All rights reserved.