IOS实现自定义布局瀑布流

2020-01-14 18:52:33刘景俊

当尺寸改变时,是否更新布局


- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
  //默认返回YES
}

布局UICollectionView的元素


- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
  //该方法需要返回rect区域中所有元素布局属性的数组
}
- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
  //该方法返回indexPath位置的元素的布局属性
}

修改UICollectionView停止滚动是的偏移量


- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
  //返回值是,UICollectionView最终停留的点
}

三、示例
1、实现效果

IOS实现自定义布局瀑布流

2、实现思路

  • 通过UICollectionView实现
  • 自定义布局,即横向流水布局和圆形普通布局
  • 通过UICollectionView的代理方法,当点击cell时,将其删除
  • 通过监听UIView的触摸事件,当点解控制器的view时更改布局

    3、实现步骤
    自定横向流水布局
    初始化布局

    
    - (void)prepareLayout
    {
      [super prepareLayout];
      //设置滚动方向
      self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
      //设置内边距
      CGFloat inset = (self.collectionView.frame.size.width - self.itemSize.width) * 0.5;
      self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);
    }
    

    指定当尺寸改变时,更新布局

    
    - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
    {
      return YES;
    }
    

    设置所有元素的布局属性

    
    - (nullable NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
    {
      //获取rect区域中所有元素的布局属性
      NSArray *array = [super layoutAttributesForElementsInRect:rect];
    
      //获取UICollectionView的中点,以contentView的左上角为原点
      CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;
    
      //重置rect区域中所有元素的布局属性,即基于他们距离UICollectionView的中点的剧烈,改变其大小
      for (UICollectionViewLayoutAttributes *attribute in array)
      {
        //获取距离中点的距离
        CGFloat delta = ABS(attribute.center.x - centerX);
        //计算缩放比例
        CGFloat scale = 1 - delta / self.collectionView.bounds.size.width;
        //设置布局属性
        attribute.transform = CGAffineTransformMakeScale(scale, scale);
      }
    
      //返回所有元素的布局属性
      return [array copy];
    }