1 year ago

#65767

test-img

dimazava

UICollectionViewCompositionalLayout Equal item height

I’ve faced the issue of setting the two cells in horizontal group equal height (= height of largest cell in the row). Now it looks almost like intended

enter image description here

But I need the left (smaller) cell’s height == right (bigger) cells height. Label has no constrained height (so can be easily increased), only binded to superview/topview edges, image has fix height, binded to superview and label as well. Cell’s height designed to be dynamic, there could be 1 line in first cell, and 3 lines in second, or 2 lines in both for example.

What have been done to achieve current implementation:

    let numOfColumns = 2

    let numOfGroups = (items.count.float / numOfColumns.float).ceil.int

    var groups = [NSCollectionLayoutItem]()

    let itemSize = NSCollectionLayoutSize(
      widthDimension: .fractionalWidth(0.5),
      heightDimension: .estimated(120)
    )
    let item = NSCollectionLayoutItem(layoutSize: itemSize)

    let localGroupSize = NSCollectionLayoutSize(
      widthDimension: .fractionalWidth(1),
      heightDimension: .estimated(120)
    )

    (0..<numOfGroups).forEach { _ in
      let currentGroup = NSCollectionLayoutGroup.horizontal(layoutSize: localGroupSize,
                                 subitem: item,
                                 count: numOfColumns)
      currentGroup.interItemSpacing = .fixed(8)
      groups.append(currentGroup)
    }

    let groupSize = NSCollectionLayoutSize(
      widthDimension: .fractionalWidth(1),
      heightDimension: .estimated(CGFloat(numOfGroups) * 120)
    )
    group = .vertical(layoutSize: groupSize, subitems: groups)
    let section = NSCollectionLayoutSection(group: group)

There're couple of same issues like: UICollectionViewCompositionalLayout equal item height using autolayout and How to create a grid layout with equal row heights using UICollectionViewCompositionalLayout and https://forums.raywenderlich.com/t/help-with-collectionview-compositional-layout/102784 but the desired result wasn't achieved/answer wasn't provided.

Thanks in advance.

UPD: Setting item size as .fractionalHeight(1) while leaving group's size as it is (.estimated(120)), which can be considered as possible solution, makes situation even worse, setting the cell's height just to 120 unconditionally.

enter image description here

UPD2:

Desired layout (copied from the linked issue)

+------+--+------+
|~~~~~~|  |~~~~~~|
|~~~~~~|  |~~~~~~|
|~~~~~~|  |~~~~~~|
|~~~~~~|  |      |
+------+--+------+

Current result

+------+--+------+
|~~~~~~|  |~~~~~~|
|~~~~~~|  |~~~~~~|
|~~~~~~|  |~~~~~~|  
|~~~~~~|      
+------+--+------+

ios

uicollectionview

uicollectionviewcompositionallayout

0 Answers

Your Answer

Accepted video resources