UICollectionViewCompositionalLayout incorrect item size

1.4k views Asked by At

I'm currently facing an issue with compositional layout which can also be seen in Apple's example -> ConferenceNewsFeedViewController. The item height is set to .estimated(100) and the width is set to .fractionalWidth(1.0). On the initial display the cell is not wrapping the label content. Only if you begin to scroll the layout of the cells are corrected. Does anybody know how to fix this issue?

Here is the incorrect layout:

incorrect layout

Here is the layout after scrolling:

correct layout

I know that it can be "fixed" with the following, but this feels more like a dirty work around:

DispatchQueue.main.async {
            self.collectionView.collectionViewLayout.invalidateLayout()
        }

Any help to this is appreciated.

Best, Carsten

3

There are 3 answers

1
Parvin Mehrabani On

you can use this method for set size for your cells.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: width, height: height)

}

0
ekranac On

I've spent days looking into this issue, trying everything I could find and think of.

Some other cells in the collection view were self sizing just fine, only a couple didn't. They had similar layout and content logic. The thing that miraculously made it work was removing the prepareForReuse() method from the collection view cell.

0
dezinezync On

I've been facing the same issue myself. In my case, I have the following setup:

  • CellSubclass: UICollectionViewListCell
    • CellContentView: UIContentView

in my CellContentView, I've overridden the layoutSubviews as such:

override func layoutSubviews() {
    super.layoutSubviews()
    invalidateIntrinsicContentSize()   
}

There are still some minor glitches sometimes, but this is better than having the wrong layout on load.