UICollection View Flow Layout Vertical Align

后端 未结 10 2142
無奈伤痛
無奈伤痛 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
    闹比i (楼主)
    2021-02-03 22:04

    This may or may not work for your particular situation, but I had some luck subclassing UICollectionViewFlowLayout in the following way:

    @interface CustomFlowLayout : UICollectionViewFlowLayout
    @end
    
    @implementation CustomFlowLayout
    
    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
        NSArray* attributesToReturn = [super layoutAttributesForElementsInRect:rect];
        for (UICollectionViewLayoutAttributes* attributes in attributesToReturn) {
            if (nil == attributes.representedElementKind) {
                NSIndexPath* indexPath = attributes.indexPath;
                attributes.frame = [self layoutAttributesForItemAtIndexPath:indexPath].frame;
            }
        }
        return attributesToReturn;
    }
    
    - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
        UICollectionViewLayoutAttributes *currentItemAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
    
        currentItemAttributes.frame = CGRectOffset(currentItemAttributes.frame, 0, 0.5 * CGRectGetHeight(currentItemAttributes.frame));
    
        return currentItemAttributes;
    }
    
    @end
    

提交回复
热议问题