Using mixed fractional and absolute values to size a NSCollectionLayoutItem

831 Views Asked by At

I am sizing a NSCollectionLayoutItem in its group. Using NSCollectionLayoutSize and NSCollectionLayoutDimension I can achieve requirements such as ‘I want it to be half the width of its container’ or ' I want it to be 200px’ or ’I want its height to be the same as its width plus 10%’.

But I can’t find a way to implement what I need: ‘I want its height to be the same as its width plus 28px’.

Is that possible at all?

Code:

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
}()
1

There are 1 best solutions below

0
On

You can compute the fractional values yourself, add a constant and give it to the Layout object as absolute.

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