自定义UICollectionViewFlowLayout的时候可能会遇到这样的警告:
UICollectionViewFlowLayout has cached frame mismatch for index path <NSIndexPath: xxx> {length = xx, path = xx} - cached value: {{xx, xx}, {xx, xx}}; expected value: {{xx, xx}, {xx, xx}}.
This is likely occurring because the flow layout subclass xxx is modifying attributes returned by UICollectionViewFlowLayout without copying them.
警告说的很清楚。我们在自定义的layout里最好不要直接修改UICollectionViewLayoutAttributes,而是copy出来一份之后再修改。
示例代码如下:
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let collectionView = collectionView,
let origin = super.layoutAttributesForElements(in: rect) else { return nil }
// copy一份原数据
let copied = NSArray.init(array: origin, copyItems: true) as! [UICollectionViewLayoutAttributes]
for atts in copied {
/**
在这里对Attributes进行修改。
修改的是copy后的Attributes,不是直接通过super.layoutAttributesForElements(in: rect)获取的数据,
也就不会有警告了。
*/
}
return copied
}
网友评论