- 只有系统达不到我们想要的效果,我们就可以自定义
创建一个类继承UICollectionViewFlowLayout,这个类就是自定义的流水布局(FlowLayout)
重写他的方法,扩展功能
/*
什么时候调用:collectionView第一次布局,collectionView刷新的时候也会调用
作用:计算cell的布局,条件:cell的位置是固定不变的
*/
- (void)prepareLayout{
[super prepareLayout];
}
/*
作用:计算collectionView滚动范围
*/
- (CGSize)collectionViewContentSize{
return [super collectionViewContentSize];
}
/*
作用:指定一段区域(rect)给你这段区域内cell的尺寸
可以一次性返回所有cell尺寸,也可以每隔一个距离返回cell
UICollectionViewLayoutAttributes:确定cell的尺寸
一个UICollectionViewLayoutAttributes对象就对应一个cell
拿到UICollectionViewLayoutAttributes就相当于拿到cell
*/
- (NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
NSArray *attrs = [super layoutAttributesForElementsInRect:rect];
int i = 0;
for (UICollectionViewLayoutAttributes *attr in attrs) {
if (i == 0) {
attr.transform = CGAffineTransformMakeScale(0.5, 0.5);
}
i++;
}
return attrs;
}
/*
Invalidate:刷新
作用:在滚动的时候是否允许刷新布局
*/
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
return NO;
}
/*
什么时候调用:用户手指一松开就会调用
作用:确定最终偏移量
拖动比较快,最终偏移量不等于手指离开时偏移量
*/
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{
//最终偏移量
CGPoint targetP = [super targetContentOffsetForProposedContentOffset:proposedContentOffset withScrollingVelocity:velocity];
//手指偏移量
self.collectionView.contentOffset;
//如果我们返回CGPointZero,我们拖动到哪里,就会自动返回到原点
return targetP;
}