UICollection View Flow Layout Vertical Align

后端 未结 10 2263
無奈伤痛
無奈伤痛 2021-02-03 21:45

By default, when you are using the flow layout in a collection view, cells are centered vertically. Is there a way to change this alignment ?

10条回答
  •  萌比男神i
    2021-02-03 22:06

    following code worked for me

    @interface TopAlignedCollectionViewFlowLayout : UICollectionViewFlowLayout
    
    - (void)alignToTopForSameLineElements:(NSArray *)sameLineElements;
    
    @end
    
    @implementation TopAlignedCollectionViewFlowLayout
    
    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect;
    {
        NSArray *attrs = [super layoutAttributesForElementsInRect:rect];
        CGFloat baseline = -2;
        NSMutableArray *sameLineElements = [NSMutableArray array];
        for (UICollectionViewLayoutAttributes *element in attrs) {
            if (element.representedElementCategory == UICollectionElementCategoryCell) {
                CGRect frame = element.frame;
                CGFloat centerY = CGRectGetMidY(frame);
                if (ABS(centerY - baseline) > 1) {
                    baseline = centerY;
                    [self alignToTopForSameLineElements:sameLineElements];
                    [sameLineElements removeAllObjects];
                }
                [sameLineElements addObject:element];
            }
        }
        [self alignToTopForSameLineElements:sameLineElements];//align one more time for the last line
        return attrs;
    }
    
    - (void)alignToTopForSameLineElements:(NSArray *)sameLineElements
    {
        if (sameLineElements.count == 0) {
            return;
        }
        NSArray *sorted = [sameLineElements sortedArrayUsingComparator:^NSComparisonResult(UICollectionViewLayoutAttributes *obj1, UICollectionViewLayoutAttributes *obj2) {
            CGFloat height1 = obj1.frame.size.height;
            CGFloat height2 = obj2.frame.size.height;
            CGFloat delta = height1 - height2;
            return delta == 0. ? NSOrderedSame : ABS(delta)/delta;
        }];
        UICollectionViewLayoutAttributes *tallest = [sorted lastObject];
        [sameLineElements enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes *obj, NSUInteger idx, BOOL *stop) {
            obj.frame = CGRectOffset(obj.frame, 0, tallest.frame.origin.y - obj.frame.origin.y);
        }];
    }
    
    @end
    

提交回复
热议问题