Warning: UICollectionViewFlowLayout has cached fra

2019-01-11 12:42发布

This is the code causing the warning:

private override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
    let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)
    let distance = CGRectGetMidX(attributes!.frame) - self.midX;
    var transform = CATransform3DIdentity;
    transform = CATransform3DTranslate(transform, -distance, 0, -self.width);
    attributes!.transform3D = CATransform3DIdentity;
    return attributes
}

The console also prints:

This is likely occurring because the flow layout "xyz" is modifying attributes returned by UICollectionViewFlowLayout without copying them.

How do I fix this warning?

7条回答
Lonely孤独者°
2楼-- · 2019-01-11 13:37

I had this issue when overriding layoutAttributesForElementsInRect. Iterating through each element in the super.layoutAttributesForElementsInRect(rect) array and calling copy wasn't working for me, so I ended up falling back on Foundation classes and using NSArray's copyItems:

override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    // unwrap super's attributes
    guard let superArray = super.layoutAttributesForElementsInRect(rect) else { return nil }

    // copy items
    guard let attributes = NSArray(array: superArray, copyItems: true) as? [UICollectionViewLayoutAttributes] else { return nil }

    // modify attributes

    return attributes
}
查看更多
登录 后发表回答