UICollectionViewCells are resetting their size on refresh

Recently I was working on a scrollable tab bar, where I decided to use collectionview with estimatedSize as automatic as the tab titles were dynamic. I used a stackView inside the cell with all proper constraints and used the default flowlayout. Everything worked well unless there was a requirement to reload the tabs and what happened was once the reload happens, size of the cells became wrong, they shrinked suddenly. I could use the sizeForItem api but then I loose the dynamic behavior. Finally below are the steps that I did.

I was creating the layout programmatically

  1. Set translatesAutoresizingMaskIntoConstraints false on ContentView
contentView.translatesAutoresizingMaskIntoConstraints = false

This step fixed the layout reset, but it thrown a lot of constraint warning saying that contentView is not constrained. Again, normally it is not advised to make translatesAutoresizingMaskIntoConstraints = false on contentView but I didnt have an option.

2. In the custom cell override preferredLayoutAttributesFitting

    override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
        setNeedsLayout()
        layoutIfNeeded()
        let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
        var updatedFrame = layoutAttributes.frame
        updatedFrame.size = size
        layoutAttributes.frame = updatedFrame
        return layoutAttributes
    }

After doing the above steps, reset issue was fixed and the contraint warnings/ errors also went away. Hope it helped, this particular issue has killed a lot of my time, hope it helps

Leave a Reply

Your email address will not be published.