自定義UICollectionViewFlowLayout的時(shí)候可能會(huì)遇到這樣的警告:
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一份原數(shù)據(jù)
let copied = NSArray.init(array: origin, copyItems: true) as! [UICollectionViewLayoutAttributes]
for atts in copied {
/**
在這里對Attributes進(jìn)行修改权逗。
修改的是copy后的Attributes混聊,不是直接通過super.layoutAttributesForElements(in: rect)獲取的數(shù)據(jù),
也就不會(huì)有警告了漾稀。
*/
}
return copied
}