提问人:danu 提问时间:10/4/2023 最后编辑:danu 更新时间:10/4/2023 访问量:30
使用 UICollectionViewCompositionalLayout 在 iPad 上并排显示项目
Display Items Side by side on iPad using UICollectionViewCompositionalLayout
问:
我的目的是在 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
}
答:
1赞
DonMag
10/4/2023
#1
看来你设置错了......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)
你应该得到你想要的结果。
评论