1

我对自定义 UICollectionViewFlowLayout 有一个奇怪的问题,我的单元格包含一个 imageView,我对我的单元格应用了缩放效果......但是我认为我在缩放效果上做错了,这很奇怪,因为我的单元格得到正确缩放,问题是某些单元格的 imageView 不是。

这是此问题的相关代码(我认为),(请注意,如果我删除方法:- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect或 CATransform3DMakeScale,问题似乎不会出现。)

///// UICollectionViewController.m


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HICollectionViewCell *cell = (HICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:COLLECTION_VIEW_CELL_ID forIndexPath:indexPath];
    [self customizeCell:cell atIndexPath:indexPath];
    return cell;
}

#pragma mark - CollectionView FlowDelegate

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(200.0f, 200.0f);
}

#pragma mark - "Private" Methods

- (void)customizeCell:(HICollectionViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    UIImageView *view = (UIImageView *)[cell.contentView viewWithTag:kCollectionViewCellSubViewTag_imgView];
    if (!view.image) {
        view.image = [UIImage imageNamed:@"placeholder.png"];
    }
}

自定义布局继承自 UICollectionViewFlowLayout

/////// CustomLayout.m

static const CGFloat ACTIVE_DISTANCE = 200.0f;
static const CGFloat ZOOM_FACTOR = 0.3f;

- (id)init
{
    if(self = [super init]) {
        self.itemSize = CGSizeMake(ITEM_SIZE, ITEM_SIZE);
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.sectionInset = UIEdgeInsetsMake(200.0f, 0.0f, 200.0f, 0.0f);
        self.minimumLineSpacing = 50.0f;
    }

    return self;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    CGRect visibleRect;
    visibleRect.origin = self.collectionView.contentOffset;
    visibleRect.size = self.collectionView.bounds.size;

    for (UICollectionViewLayoutAttributes *attribute in attributes) {
        if (CGRectIntersectsRect(attribute.frame, rect)) {
            CGFloat distance = CGRectGetMidX(visibleRect) - attribute.center.x;
            CGFloat normalizedDistance = distance / ACTIVE_DISTANCE;

            // Apply a zoom factor to cells within ACTIVE_DISTANCE
            if (ABS(distance) < ACTIVE_DISTANCE) {
                CGFloat zoom = 1.0f + ZOOM_FACTOR * (1.0f - ABS(normalizedDistance));
                attribute.transform3D = CATransform3DMakeScale(zoom, zoom, 1.0);
                attribute.zIndex = round(zoom);
            }
        }
    }

    return attributes;
}

随着 FlowLayout 的出现,一切看起来都很好。

图 1

然后我开始滚动,我注意到右侧单元格的背景层开始炫耀(背景颜色为橙色

图 2

如您所见,在两个单元格之后,第三个单元格(开始出现,再次看起来正常)。

图 3

也许这是单元队列和出队的问题(以及被重用的 imageView 还是什么?)。

4

0 回答 0