collectionview cell吸顶效果

时间:2023-03-09 09:41:07
collectionview cell吸顶效果

#import "MyFlowLayout.h"

@implementation MyFlowLayout

#define kWidth self.collectionView.frame.size.width

- (instancetype)init

{

if (self = [super init]) {

// 设置item估计值

self.estimatedItemSize = CGSizeMake(300, 100);

// 全局配置item尺寸,单独定义调用协议方法[sizeForItemAtIndexPath]

self.itemSize = CGSizeMake(300, 100);

// 全局配置每行之间的间距,单独定义可调用协议方法[minimumLineSpacingForSectionAtIndex]

self.minimumLineSpacing = 10;

// 全局配置每行内部item的间距,单独定义可调用协议方法[minimumInteritemSpacingForSectionAtIndex]

self.minimumInteritemSpacing = 0;

// 设置滚动方向

// UICollectionViewScrollDirectionVertical

// UICollectionViewScrollDirectionHorizontal

self.scrollDirection = UICollectionViewScrollDirectionVertical;

// 设置是否当元素超出屏幕之后固定头部视图位置,默认NO;

self.sectionHeadersPinToVisibleBounds = YES;

// 设置是否当元素超出屏幕之后固定尾部视图位置,默认NO;

self.sectionFootersPinToVisibleBounds = YES;

}

return self;

}

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

{

// 拿到可见区域布局属性

NSArray *arr = [super layoutAttributesForElementsInRect:rect];

// 处理当前可见区内的布局属性吸顶

[arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

[self recomputeCellAttribute:obj];

}];

return arr;

}

- (void)recomputeCellAttribute:(UICollectionViewLayoutAttributes *)attrib

{

// 获得悬停的Y值

CGFloat minY = CGRectGetMinY(self.collectionView.bounds) + self.collectionView.contentInset.top;

//拿到布局属性应该出现的位置

CGFloat finalY = MAX(minY, attrib.frame.origin.y);

CGPoint point = attrib.frame.origin;

point.y = finalY;

attrib.frame = (CGRect){point,attrib.frame.size};

//根据IndexPath设置zIndex能确立顶部悬停的cell被后来的cell覆盖的层级关系

attrib.zIndex = attrib.indexPath.row;

}

- (NSArray<NSString *>*)arrStr

{

return @[@"f",@1];

}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds

{

return YES;

}

@end