user8873209
user8873209

Reputation:

Dynamic width size problem in UICollectionView Cell

I dynamically set width of each cell of UICollectionView according to text inside it. The problem is that most of the time the width size is correct but sometimes cell size is not correct.

These are strings i displayed in cell

let tabs = ["1st tab", "Second Tab Second", "Third Tab", "4th Tab", "A"]

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

    let text = tabs[indexPath.row]

    let font = UIFont.systemFont(ofSize: 21, weight: UIFont.Weight.regular)
    let attributes = font != nil ? [NSAttributedString.Key.font: font] : [:]
    let width = text.size(withAttributes: attributes).width

    return CGSize(width: width + 16+16+16+35, height: self.menuBarColView.frame.height)

}

It correctly displayed 1st, second, third and 5th one but size of 4th cell is wrong. This is the output.

enter image description here

Please tell me where is the problem?

Upvotes: 1

Views: 1247

Answers (2)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119310

Selfsize collection view cell checklist:

  • Set estimated item size to anything but .zero. Works best if you set it to (1,1)

example:

(collectionView?.collectionViewLayout as? UICollectionViewFlowLayout)?.estimatedItemSize = CGSize(width: 1, height: 1)
  • Layout cell contents and check if it works if scalable content changes.
  • Return the actual size if you can calculate it without loosing performance
  • Double check to reduce codes that repeats and cache sizes.

If you are targeting iOS 10 and above, you can use this instead:

....estimatedItemSize = UICollectionViewFlowLayout.automaticSize

Upvotes: 2

Hakan Baybas
Hakan Baybas

Reputation: 104

I couldn't see the pictures cause of my VPN and I see that you fixed the problem, however, I want to add something, If your cells use auto layout and have constraints you need to calculate and change them too.

Upvotes: 0

Related Questions