简体   繁体   中英

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.

在此处输入图片说明

Please tell me where is the problem?

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

我看不到 VPN 的图片原因,我看到您解决了问题,但是,我想添加一些内容,如果您的单元格使用自动布局并且有约束,您也需要计算和更改它们。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM