添加动态更改单元格宽度的UICollectionViewCell会使minimumInteritemSpacing无效?

时间:2016-04-03 16:59:16

标签: ios objective-c uicollectionview uicollectionviewcell uicollectionviewlayout

在演示项目中,我可以按“添加新标签”按钮添加UICollectionViewCell,标签包含我新输入的文本。

这是目标效果:

target effect

这是目前的情况: wrong effect

在当前状态下,我在cellForItemAtIndexPath函数中重新配置单元格UI并在sizeForItemAtIndexPath函数中调整单元格大小。但是这些操作似乎导致minimumInteritemSpacing不起作用。我使用UICollectionViewFlowLayout。

1 个答案:

答案 0 :(得分:0)

我认为你可以继承UICollectionViewFlowLayout,并覆盖方法 -

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

#import <UIKit/UIKit.h>  
@interface CustomViewFlowLayout : UICollectionViewFlowLayout

@property(nonatomic) CGFloat maximumLineSpacing;

@end

@implementation CustomlViewFlowLayout

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *answer = [super layoutAttributesForElementsInRect:rect];
    for(int i = 1; i < answer.count; ++i) {
        UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
        UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1];

        NSInteger maximumSpacing = self.maximumLineSpacing;
        NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);

        if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = origin + maximumSpacing;
            currentLayoutAttributes.frame = frame;
        }
        if (currentLayoutAttributes.frame.origin.y != prevLayoutAttributes.frame.origin.y) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = 0;
            currentLayoutAttributes.frame = frame;
        }
    }
    return answer;
}

@end

用于设置最大行空间的属性maximumLineSpacing