OC转Swift:UICollectionViewLayout子类设置contentSize报错问题
解决Swift中自定义UICollectionViewLayout设置contentSize的错误
嘿,这个问题我之前从OC转Swift的时候也踩过坑!原因很简单:Swift把UICollectionViewLayout的contentSize从OC里的可写属性改成了只读的计算属性,所以你直接像OC那样赋值肯定会报错。
下面是具体的解决步骤,照着做就行:
首先在你的自定义布局类里加一个私有存储属性,用来保存我们计算好的内容尺寸:
private var _contentSize: CGSize = .zero在
prepare()方法里,按照原来的逻辑计算contentWidth和contentHeight,然后把结果赋值给这个存储属性:override func prepare() { super.prepare() // 这里替换成你原来OC里计算contentWidth和contentHeight的逻辑 let contentWidth: CGFloat = // 你的计算代码 let contentHeight: CGFloat = // 你的计算代码 // 把最终尺寸存到我们的私有属性里 _contentSize = CGSize(width: contentWidth, height: contentHeight + 40) }最后重写
contentSize这个计算属性,返回我们存储的尺寸:override var contentSize: CGSize { return _contentSize }
完整的自定义布局类示例大概是这样:
class MyCustomCollectionViewLayout: UICollectionViewLayout { private var _contentSize: CGSize = .zero override func prepare() { super.prepare() // 模拟你的尺寸计算逻辑,替换成实际代码 let contentWidth = collectionView?.bounds.width ?? 0 let contentHeight = 300 // 假设这是你计算出来的高度 _contentSize = CGSize(width: contentWidth, height: contentHeight + 40) } override var contentSize: CGSize { return _contentSize } // 别忘了重写其他必要的方法,比如返回布局属性的方法 override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { // 你的逻辑代码 return [] } }
本质上就是用一个私有存储属性来缓存计算好的尺寸,然后通过重写只读的contentSize属性把它暴露出去,这是Swift对UICollectionViewLayout API的规范调整,目的是让布局的尺寸逻辑更清晰可控。
内容的提问来源于stack exchange,提问作者Sjakelien
相关产品推荐
相关产品推荐

