UICollectionView Cell中的动态宽度大小问题 [英] Dynamic width size problem in UICollectionView Cell

查看:99
本文介绍了UICollectionView Cell中的动态宽度大小问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我根据里面的文字动态设置UICollectionView的每个单元格的宽度.问题是大多数时候 width 大小是正确的,但有时单元格大小不正确.

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)

}

它正确显示了第一个、第二个、第三个和第 5 个,但第 4 个单元格的大小错误.这是输出.

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:

Selfsize collection view cell checklist:

  • 估计的项目大小设置为除.zero以外的任何内容.如果将其设置为 (1,1) 效果最佳
  • Set estimated item size to anything but .zero. Works best if you set it to (1,1)

示例:

(collectionView?.collectionViewLayout as? UICollectionViewFlowLayout)?.estimatedItemSize = CGSize(width: 1, height: 1)

  • 布局单元格内容并检查它是否在可缩放内容发生变化时起作用.
  • 如果可以在不降低性能的情况下进行计算,则返回实际大小
  • 双重检查以减少重复的代码和缓存大小.
  • 如果您的目标是 iOS 10 及更高版本,则可以改用它:

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

    ....estimatedItemSize = UICollectionViewFlowLayout.automaticSize
    

    这篇关于UICollectionView Cell中的动态宽度大小问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆