使用UICollectionViewCompositionalLayout
,我想在一个组中呈现特定数量的项目,在另一组中呈现特定数量的项目
这是我想出的布局的简化版本:
func createTestSectionLayout(noTextItems: Int, noImageItems: Int) -> NSCollectionLayoutSection {
// noTextItems texts can have different lengths
let textItemSize = NSCollectionLayoutSize(widthDimension: .estimated(80),
heightDimension: .estimated(44))
var textItems = [NSCollectionLayoutItem]()
for _ in 0..<noTextItems {
textItems.append(NSCollectionLayoutItem(layoutSize: textItemSize))
}
let textGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.6), heightDimension: .estimated(44))
let textGroup = NSCollectionLayoutGroup.horizontal(layoutSize: textGroupSize, subitems: textItems)
// noImageItems images should be rendered with their intrinsic size
let imageItemSize = NSCollectionLayoutSize(widthDimension: .estimated(80),
heightDimension: .estimated(44))
var imageItems = [NSCollectionLayoutItem]()
for _ in 0..<noImageItems {
imageItems.append(NSCollectionLayoutItem(layoutSize: imageItemSize))
}
let iamgeGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.4), heightDimension: .estimated(44))
let imageGroup = NSCollectionLayoutGroup.horizontal(layoutSize: iamgeGroupSize, subitems: imageItems)
// group that contains textGroup and imageGroup
let lineGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .estimated(44))
let lineGroup = NSCollectionLayoutGroup.horizontal(layoutSize: lineGroupSize, subitems: [textGroup,imageGroup])
print(lineGroup.visualDescription())
print()
let section = NSCollectionLayoutSection(group: lineGroup)
return section
}
作为一个例子,我用
let test = self.createTestSectionLayout(noTextItems: 2, noImageItems: 3)`
结果print(lineGroup.visualDescription())
很有趣,说明了我的问题:
+-------+-------+-------+-------+-------+-------+- ------+---+-------+-------+-------+-------+------- + | | | | | | | | | | | | | | +-------+-------+-------+-------+-------+-------+- ------+ +-------+-------+-------+-------+-------+ | | | | | | | +-------------------------------------------------- -------------------------------------------------- +
该 ascii 图形中的每个小块都是可以(并且正在)渲染项目的位置。
因此,鉴于要渲染的项目足够小,所有 5 个项目(2 个文本,3 个图像)都在左侧 textGroup 中渲染,即使该组仅包含 2 个NSCollectionLayoutItem
.
我的实验表明,这种意外行为受.fractionalWidth(0.6)
群体规模的控制。一旦我使用它,就会UICollectionViewCompositionalLayout
忽略我在该组中指定的项目数。
UICollectionViewCompositionalLayout
如果我将组宽度设置为.estimated(200)
. 但这弄乱了我的完整布局并使其无法使用。
如何控制组中的项目数并具有由指定的组宽度.fractionalWidth(0.6)
?我希望如果它们不适合排成一行,我会得到一个换行符,因为我给出了一个分数宽度和该组的估计高度。