Reputation:
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.
Please tell me where is the problem?
Upvotes: 1
Views: 1247
Reputation: 119310
Selfsize collection view cell checklist:
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)
If you are targeting iOS 10 and above, you can use this instead:
....estimatedItemSize = UICollectionViewFlowLayout.automaticSize
Upvotes: 2
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