OStack程序员社区-中国程序员成长平台

标题: ios - UICollectionViewCell 位置翻倍 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 11:40
标题: ios - UICollectionViewCell 位置翻倍

我刚刚注意到 uicollectionviewcells 的中心是真实中心的一半。

示例:

将单元格的框架设置为:

[0] {{0, 0}, {100, 100}}
[1] {{100, 100}, {100, 100}}
[2] {{200, 200}, {100, 100}}
[3] {{300, 300}, {100, 100}}
[4] {{400, 400}, {100, 100}}
[5] {{500, 500}, {100, 100}}

注意:这是我从 setFrame 得到的值,applyLayoutAttributes:

看起来像这样: actual look

但应该是这样的: how it should look

UICollectionViewLayout子类的实现

@implementation CVTLayout

- (void)prepareLayout {
    [super prepareLayout];

    CollectionViewTable *cvt = (CollectionViewTable*)self.collectionView;


    CGSize size = CGSizeMake(100, 100);
    CGPoint center = CGPointMake(50, 50);
    NSMutableArray *cellAttributes = [[NSMutableArray alloc] init];
    for (int item = 0; item < [cvt.cellValues count]; item++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:0];
        UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        attributes.size = size;
        attributes.center = center;
        [cellAttributes addObject:attributes];

        center.x += size.width;
        center.y += size.height;
    }
    cvt.cellAttributes = cellAttributes;
}

- (CGSize)collectionViewContentSize {
    return self.collectionView.bounds.size;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPathNSIndexPath *)indexPath {
    CollectionViewTable *cvt = (CollectionViewTable*)self.collectionView;
    return cvt.cellAttributes[indexPath.item];
}

- (NSArray *)layoutAttributesForElementsInRectCGRect)rect {
    NSMutableArray *layoutAttributes = [[NSMutableArray alloc] init];
    CollectionViewTable *cvt = (CollectionViewTable*)self.collectionView;
    for (UICollectionViewLayoutAttributes *cellAttributes in cvt.cellAttributes) {
        if (CGRectIntersectsRect(rect, cellAttributes.frame)) {
            [layoutAttributes addObject:cellAttributes];
        }
    }
    return layoutAttributes;
}

- (BOOL)shouldInvalidateLayoutForBoundsChangeCGRect)newBounds {
    return false;
}

@end



Best Answer-推荐答案


问题是将 cell-label-frame 设置为 cell-frame 而不是 cell-bounds...

关于ios - UICollectionViewCell 位置翻倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16961009/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4