我正在努力使用UICollectionViewCompositionalLayout获得我想要的布局。下面的图像是我正在尝试做的(连同我对fractionalWidth/Height的计算,根据我得到的结果,我只能假设它是不正确的。
Nested group with Leading Item - design
我为尝试生成上述代码而编写的代码如下:
let leadingItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1/4), heightDimension: .fractionalHeight(1))
let nestedGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(3/4), heightDimension: .fractionalHeight(1))
let nestedItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1/3), heightDimension: .fractionalHeight(1/2))
let outerGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalWidth(3/5))
let leadingItem = NSCollectionLayoutItem(layoutSize: leadingItemSize)
let nestedItem = NSCollectionLayoutItem(layoutSize: nestedItemSize)
let nestedGroup = NSCollectionLayoutGroup.horizontal(layoutSize: nestedGroupSize, subitem: nestedItem, count: 3)
let outerGroup = NSCollectionLayoutGroup.horizontal(layoutSize: outerGroupSize, subitems: [leadingItem, nestedGroup])
let section = NSCollectionLayoutSection(group: outerGroup)
return section这会产生不需要的结果,如下图所示:
Nested group with Leading Item - Preview
谁能解释一下我做错了什么,并帮我弄清楚如何实现我想要做的事情?
谢谢。:)
发布于 2021-03-12 16:19:27
所以我设法修复了它,添加了一个包含两个水平组的垂直组。我不知道这是不是正确的方法,如果有人能验证和解释为什么这是正确的,或者解释最好的方法是什么,我会非常感激。我的结果代码如下:
let leadingItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1/4), heightDimension: .fractionalHeight(1))
let nestedHorizontalGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(1/2))
let nestedHorizontalItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1/3), heightDimension: .fractionalHeight(1))
let outerGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalWidth(3/5))
let nestedVerticalGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(3/4), heightDimension: .fractionalHeight(1))
let leadingItem = NSCollectionLayoutItem(layoutSize: leadingItemSize)
leadingItem.contentInsets.trailing = 1
let nestedHorizontalItem = NSCollectionLayoutItem(layoutSize: nestedHorizontalItemSize)
let nestedHorizontalGroup = NSCollectionLayoutGroup.horizontal(layoutSize: nestedHorizontalGroupSize, subitem: nestedHorizontalItem, count: 3)
nestedHorizontalGroup.interItemSpacing = .fixed(1)
let nestedVerticalGroup = NSCollectionLayoutGroup.vertical(layoutSize: nestedVerticalGroupSize, subitem: nestedHorizontalGroup, count: 2)
nestedVerticalGroup.interItemSpacing = .fixed(1)
let outerGroup = NSCollectionLayoutGroup.horizontal(layoutSize: outerGroupSize, subitems: [leadingItem, nestedVerticalGroup])
outerGroup.contentInsets = .init(top: 2, leading: 0, bottom: 2, trailing: 0)
let section = NSCollectionLayoutSection(group: outerGroup)
section.contentInsets = .init(top: 2, leading: 50, bottom: 16, trailing: 50)
return section最终结果如下图所示:
https://stackoverflow.com/questions/66591978
复制相似问题