UICollectionView实现放大缩小效果

原文地址:http://blog.csdn.net/u013282507/article/details/54136812
原文讲的特别详细,在此就是记录下,方便查找
20170106123134176.gif 要实现这样的效果总共分四步:

  1. 实现横向滚动 (UICollectionView的最基础实现)
  2. 缩进效果
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { return UIEdgeInsetsMake(0, [self collectionInset], 0, [self collectionInset]); }

  1. 居中放大
    重写UICollectionViewFlowLayout方法-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { NSArray *arr = [self getCopyOfAttributes:[super layoutAttributesForElementsInRect:rect]]; //屏幕中线 CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width/2.0f; //刷新cell缩放 for (UICollectionViewLayoutAttributes *attributes in arr) { CGFloat distance = fabs(attributes.center.x - centerX); //移动的距离和屏幕宽度的的比例 CGFloat apartScale = distance/self.collectionView.bounds.size.width; //把卡片移动范围固定到 -π/4到 +π/4这一个范围内 CGFloat scale = fabs(cos(apartScale * M_PI/4)); //设置cell的缩放 按照余弦函数曲线 越居中越趋近于1 attributes.transform = CGAffineTransformMakeScale(1.0, scale); } return arr }

    //防止报错 先复制attributes
    • (NSArray *)getCopyOfAttributes:(NSArray *)attributes
      {
      NSMutableArray *copyArr = [NSMutableArray new];
      for (UICollectionViewLayoutAttributes *attribute in attributes) {
      [copyArr addObject:[attribute copy]];
      }
      return copyArr;
      }
    //是否需要重新计算布局
    -(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
    {
    return true;
    }
  2. 自动居中
    NSInteger _currentIndex; CGFloat _dragStartX; CGFloat _dragEndX;

    //手指拖动开始
    -(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
    {
    _dragStartX = scrollView.contentOffset.x;
    }
    //手指拖动停止
    -(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
    {
    _dragEndX = scrollView.contentOffset.x;
    dispatch_async(dispatch_get_main_queue(), ^{
    [self fixCellToCenter];
    });
    }
    //配置cell居中
    -(void)fixCellToCenter
    {
    //最小滚动距离
    float dragMiniDistance = self.bounds.size.width/20.0f;
    if (_dragStartX - _dragEndX >= dragMiniDistance) {
    _currentIndex -= 1; //向右
    }else if(_dragEndX - _dragStartX >= dragMiniDistance){
    _currentIndex += 1; //向左
    }
    NSInteger maxIndex = [_collectionView numberOfItemsInSection:0] - 1;
    _currentIndex = _currentIndex <= 0 ? 0 : _currentIndex;
    _currentIndex = _currentIndex >= maxIndex ? maxIndex : _currentIndex;
    【UICollectionView实现放大缩小效果】[_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:_currentIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }

    推荐阅读