高度自适应循环缩放滚动view实现

来源:互联网 发布:淘宝要五星好评话术 编辑:程序博客网 时间:2024/06/06 03:28

高度自适应循环缩放滚动view实现

项目中需要封装一个能够高度自适应的循环缩放的滚动视图,在此做下整理。
首先想到用UICollectionView实现,
继承自UICollectionViewFlowLayout 重写其中的几个方法 :

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {    NSArray *attrsArr = [super layoutAttributesForElementsInRect:rect];    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width / 2;    //可视rect    CGRect visibleRect;    visibleRect.origin = self.collectionView.contentOffset;    visibleRect.size = self.collectionView.bounds.size;    for (UICollectionViewLayoutAttributes *attr in attrsArr) {        if (CGRectIntersectsRect(attr.frame, visibleRect)) {            CGFloat distance = ABS(attr.center.x - centerX);            scale = 1 + distance * 0.03;            attr..transform = CGAffineTransformMakeScale(scale, scale);        }    }    return attrsArr;}- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {    return true;}- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {    // 1.计算中心点位置    CGFloat centerX = proposedContentOffset.x + self.collectionView.bounds.size.width * 0.5;    // 2.计算可视化区域    CGRect visibleRect;    visibleRect.origin = proposedContentOffset;    visibleRect.size = self.collectionView.bounds.size;    // 3.获取可视区域的cell的attribute对象    NSArray *attrs = [self layoutAttributesForElementsInRect:visibleRect];    CGFloat offsetdfsdfas = MAXFLOAT;    for (UICollectionViewLayoutAttributes *attr in attrs) {        if (ABS(attr.center.x - centerX) < ABS(offsetdfsdfas)) {            offsetdfsdfas = centerX - attr.center.x;        }    }    return CGPointMake(proposedContentOffset.x + offsetdfsdfas, proposedContentOffset.y);}

这样实现有个问题就是 因为每个显示的item高度不一样,所以两边的item缩放到同样高度时横向缩放比例不同,会造成每个item之间间距不一样,无法统一,所以最后还是用scrollerView实现。

效果如下:
滑动scrollerView 逐步显示图片展示界面,黑色边框为scrollerView大小,高度会随着内容的高度自动变化

step 1
step 1

step 2
step 2

step 3
step 3

具体实现请看demo

0 0