iOS UICollectionView 均分间隙处理

2023-06-08  本文已影响0人  iOS小武哥
1.当我们在开发过程中会屏幕均分成几个Item,在部分屏幕中会存在间隙问题,为了解决这个问题,直接上代码,新建FYUserCenterFlowLayout 继承 UICollectionViewFlowLayout工具类:

.h

NS_ASSUME_NONNULL_BEGIN

@interface FYUserCenterFlowLayout : UICollectionViewFlowLayout

@end

NS_ASSUME_NONNULL_END

.m

#import "FYUserCenterFlowLayout.h"

@implementation FYUserCenterFlowLayout

-(NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{

    NSMutableArray *answer = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    
    for(int i = 1; i < [answer count]; ++i) {
        UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i];
        UICollectionViewLayoutAttributes*prevLayoutAttributes=answer[i-1];
        NSInteger maximumSpacing = 0;
        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;
        }
    }
    return answer;
}

@end
上一篇 下一篇

猜你喜欢

热点阅读