1 year ago

#257316

test-img

landev

UICollectionViewCompositionalLayout two group in section


I use UICollectionViewCompositionalLayout to create UICollectionView, I want the first Item to occupy half the width, other Items to occupy 1/4 of the width, items grow downward, like this:

https://i.stack.imgur.com/uO5R9.png

but I can't achieve the coexistence of two groups in the section, this is my code:

    let compositionalLayout: UICollectionViewCompositionalLayout = {
        let inset: CGFloat = 1

        // Items
        let largeItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1))
        let largeItem = NSCollectionLayoutItem(layoutSize: largeItemSize)
        largeItem.contentInsets = NSDirectionalEdgeInsets(top: inset, leading: inset, bottom: inset, trailing: inset)

        let smallItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1))
        let smallItem = NSCollectionLayoutItem(layoutSize: smallItemSize)
        smallItem.contentInsets = NSDirectionalEdgeInsets(top: inset, leading: inset, bottom: inset, trailing: inset)

        let smallItemGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalHeight(0.5))
        let smallItemGroup = NSCollectionLayoutGroup.horizontal(layoutSize: smallItemGroupSize, subitems: [smallItem])

        // Nested Group
        let nestedGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.5), heightDimension: .fractionalHeight(1))
        let nestedGroup = NSCollectionLayoutGroup.vertical(layoutSize: nestedGroupSize, subitems: [smallItemGroup])

        // Outer Group
        let outerGroupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .fractionalWidth(0.5))
        let outerGroup = NSCollectionLayoutGroup.horizontal(layoutSize: outerGroupSize, subitems: [largeItem, nestedGroup])

        // Section
        let section = NSCollectionLayoutSection(group: outerGroup)
        section.contentInsets = NSDirectionalEdgeInsets(top: inset, leading: inset, bottom: inset, trailing: inset)

        // Supplementary Item
        let headerItemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(40))
        let headerItem = NSCollectionLayoutBoundarySupplementaryItem(layoutSize: headerItemSize, elementKind:  UICollectionView.elementKindSectionHeader, alignment: .top)
        section.boundarySupplementaryItems = [headerItem]

        let layout = UICollectionViewCompositionalLayout(section: section)

        return layout
    }()

https://i.stack.imgur.com/i88Q2.png

How should I use UICollectionViewCompositionalLayout to achieve the effect of Figure 1.

ios

swift

uicollectionview

uicollectionviewflowlayout

uicollectionviewcompositionallayout

0 Answers

Your Answer

Accepted video resources