Dynamic width size problem in UICollectionView Cell

回眸只為那壹抹淺笑 提交于 2021-02-10 17:27:35

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/52930787/dynamic-width-size-problem-in-uicollectionview-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!