使用混合小数和绝对值来调整 NSCollectionLayoutItem 的大小

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

我正在调整其组中的

NSCollectionLayoutItem
的大小。 使用
NSCollectionLayoutSize
NSCollectionLayoutDimension
我可以实现诸如以下的要求 “我希望它是容器宽度的一半”或“我希望它是 200px”或“我希望它的高度与其宽度相同加上 10%”。

但是我找不到一种方法来实现我所需要的:“我希望它的高度与其宽度相同加上28px”。

这可能吗?

代码:

private lazy var myFancyLayout: NSCollectionLayoutSection = {
        let itemSize = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(1.0),
            heightDimension: .fractionalWidth(1.0)
        )
        let item = NSCollectionLayoutItem(layoutSize: itemSize)
        
        // Make the group with width equal to half container width and with height 110% its width
        let groupSize_fractional = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(0.50),
            heightDimension: .fractionalWidth(0.50 * 1.1)
        )
        
        // Make the group with width equal to 100px and with height 110% its width
        let groupSize_absoulte = NSCollectionLayoutSize(
            widthDimension: .absolute(100),
            heightDimension: .absolute(100 * 1.1)
        )
        
        // Make the group with width equal to half container width and with height same as its width plus 20px
        let groupSize_mixed_impossibleToImplement = NSCollectionLayoutSize(
            widthDimension: .fractionalWidth(0.50),
            heightDimension: .fractionalWidth(0.50) // + 20px ??
        )
        
        let group = NSCollectionLayoutGroup.horizontal(
            layoutSize: groupSize_fractional, // or groupSize_absoulte or groupSize_mixed_impossibleToImplement
            subitem: item,
            count: 1
        )

        let section = NSCollectionLayoutSection(group: group)
        
        // ... further configuration
        
        return section
}()
ios swift xcode nscollectionview nscollectionviewlayout
2个回答
1
投票

您可以自己计算小数值,添加一个常量并将其作为绝对值传递给 Layout 对象。

let fractionalWidth = UIScreen.main.bounds.width/numberOfItems - trailinginsets - leadinginsets
let desiredHeight = fractionalHeight + 20
...
heightDimension = .absolute (desiredHeight)

0
投票

创建布局时使用此初始值设定项:

init(sectionProvider:)
。 在封口内,您会看到一个
NSCollectionLayoutEnvironment
。从那里您可以计算绝对宽度:

let groupWidth = layoutEnvironment.container.contentSize.width + 28
© www.soinside.com 2019 - 2024. All rights reserved.