[bug]collectionView 自定义布局错误

界面展示:

[bug]collectionView 自定义布局错误_第1张图片
sk01.png

拖动collectionView 的cell,控制台输出错误信息
Logging only once for UICollectionViewFlowLayout cache mismatched frame.
UICollectionViewFlowLayout has cached frame mismatch for index path {length = 2, path = 0 - 0} - cached value: {{-3.3333333333333321, 71.666666666666671}, {56.666666666666657, 56.666666666666671}}; expected value: {{-25, 50}, {100, 100}}.
This is likely occurring because the flow layout subclass SKLineLayout is modifying attributes returned by UICollectionViewFlowLayout without copying them.

解决方案:
自定义布局中:将计算好的布局数组orginalArray执行 copy到一个新的数组array中使用

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    // 获得super已经计算好的布局属性
    NSArray *orginalArray = [super layoutAttributesForElementsInRect:rect];
    NSArray *array = [[NSArray alloc] initWithArray:orginalArray copyItems:true];
    
    // 计算collectionView最中心点的x值
    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;
    
    // 在原有布局属性的基础上,进行微调

    for (UICollectionViewLayoutAttributes *attrs in array) {
        // cell的中心点x 和 collectionView最中心点的x值 的间距
        CGFloat delta = ABS(attrs.center.x - centerX);
        
        // 根据间距值 计算 cell的缩放比例
        CGFloat scale = 1 - delta / self.collectionView.frame.size.width;
        
        // 设置缩放比例
        attrs.transform = CGAffineTransformMakeScale(scale, scale);
    }
    
    return array;
}

你可能感兴趣的:([bug]collectionView 自定义布局错误)