Skip to content

cell高度不一时,设置对齐方式,cell位置错乱 #23

@wv-y

Description

@wv-y

在实现高度不一致的cell TopLeft对齐时遇到问题;
如下图:
image

上图中(0,0)设置高度是100,其他都是35,可以看到有错位;
groupLayoutAttributesForElementsByYLineWithLayoutAttributesAttrs方法中计算同一行的cell时,获取到的MidY不相等;

奇数/2时理论上得到0.5,可能因为像素对齐(猜测)UICollectionViewFlowLayout计算时赋值给LayoutAttributes的坐标不一定是0.5,导致错误调整了x坐标;

简单解决方案,MidY向上(下)取整,但感觉不够保险;ceil(CGRectGetMidY(attr.frame))

以下是我实现的另外一种方法,比较MinY和MaxY,大佬可以看看是否有更好的办法

- (NSArray *)NEWgroupLayoutAttributesForElementsByYLineWithLayoutAttributesAttrs:(NSArray *)layoutAttributesAttrs{
    // - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect 没有明确说明是按照indexPath顺序排列,sorted下更保险
    // 对传入的attributes进行排序
    NSArray *sortedAttributes = [layoutAttributesAttrs sortedArrayUsingComparator:^NSComparisonResult(UICollectionViewLayoutAttributes *attr1, UICollectionViewLayoutAttributes *attr2) {
        return [attr1.indexPath compare:attr2.indexPath];
    }];
    // 分组处理
    NSMutableArray *rows = [NSMutableArray array];
    NSMutableArray *currentRowAttributes = [NSMutableArray array];
    CGFloat currentRowMaxY = 0;
    for (UICollectionViewLayoutAttributes *attribute in sortedAttributes) {
        if (currentRowAttributes.count == 0) {
            // 第一次迭代,初始化第一组
            [currentRowAttributes addObject:attribute];
            currentRowMaxY = CGRectGetMaxY(attribute.frame);
        } else {
            if (attribute.frame.origin.y > currentRowMaxY) {
                // 开始新的一行
                [rows addObject:currentRowAttributes];
                currentRowAttributes = @[attribute].mutableCopy;
                currentRowMaxY = CGRectGetMaxY(attribute.frame);
            } else {
                // 添加到当前行
                [currentRowAttributes addObject:attribute];
                currentRowMaxY = MAX(currentRowMaxY, CGRectGetMaxY(attribute.frame));
            }
        }
    }
    // 添加最后一行
    if (currentRowAttributes.count > 0) {
        [rows addObject:currentRowAttributes];
    }
    return [rows copy];
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions