//准备开始布局
- (void)prepareLayout {}
//返回的是决定cell样式的数组
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray * attributes = [super layoutAttributesForElementsInRect:rect];
//计算中心点的contentOffset
CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width * 0.5;
//获取每一个cell的布局属性
for (UICollectionViewLayoutAttributes * attri in attributes) {
//计算每一个cell中心与中心点的contentOffset距离
CGFloat delat = ABS(attri.center.x - centerX);
//计算比例
CGFloat scales = 1 - delat / (self.collectionView.bounds.size.width);
attri.transform = CGAffineTransformMakeScale(scales, scales);
}
return attributes;
}
//实时刷新
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
return YES;
}
//targetContentOffset 调整后的contentOffset
//proposedContentOffset 滑动停止的contentOffset
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
// 计算最终的可见范围
CGRect rect;
rect.origin = proposedContentOffset;
rect.size = self.collectionView.frame.size;
// 取得cell的布局属性
NSArray * attributes = [super layoutAttributesForElementsInRect:rect];
CGFloat centerX = proposedContentOffset.x + self.collectionView.bounds.size.width * 0.5;
//获取最小间距
CGFloat minDetal = MAXFLOAT;
for (UICollectionViewLayoutAttributes *attrs in attributes) {
if (ABS(minDetal) > ABS(attrs.center.x - centerX)) {
minDetal = attrs.center.x - centerX;
}
}
// 在原有offset的基础上进行微调
return CGPointMake(proposedContentOffset.x + minDetal, proposedContentOffset.y);
}