UICollectionView中使用 UICollectionViewFlowLayout进行布局(模仿苹果相册)

时间:2023-03-08 16:24:42

现在都知道,在初始化UICollectionView的时候,必须要传入一Layout对象,进行布局管理。这也是collectionview和tableview的明显区别,通过collectionviewLayout,可以对collectionview进行更加强有力的控制。

自定义个UICollectionViewFlowLayout,重新里面的几个方法。

方法一: 每次滑动collectionview都会调用此方法,询问是否重新layout。如果returen Yes;则会调用方法二和方法三。

-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{

//

return YES;

}

方法二:

-(void)prepareLayout{

[super prepareLayout];

  //在这里,你可以在layout之前做一些其他的改动。或者什么都不做

}

方法三:在这个方法中,你可以获取到所有准备重新刷新的cell的一个布局属性:UICollectionViewLayoutAttributes,通过这个attributes,你可以改变cell的size,frame,alpha等等的布局属性。

-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{

//调用父类的方法获取。

NSArray *array = [super layoutAttributesForElementsInRect:rect];

// 计算collectionView最中心点的x值

CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width * 0.5;

// 在原有布局属性的基础上,进行微调

for (UICollectionViewLayoutAttributes *attrs in array) {

// cell的中心点x 和 collectionView最中心点的x值 的间距

CGFloat delta = ABS(attrs.center.x - centerX);

// 根据间距值 计算 cell的缩放比例

CGFloat scale = 1 - delta / self.collectionView.frame.size.width;

// 设置缩放比例

attrs.transform = CGAffineTransformMakeScale(scale, scale);

  }

  return array;

}

方法四:每次手滑动完后,都会调用。是手离开屏幕的一瞬间调用。返回一个最终的偏移量,如果想要改动的话,在这里去设置。如果不改动,直接返回proposedContentOffset就可以了。

-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{

return proposedContentOffset;

}

下面是我做的一个效果图,cell没有放图片上去,直接用了颜色标记:同样的道理,瀑布流是如此。不对之处,希望多多指教

UICollectionView中使用 UICollectionViewFlowLayout进行布局(模仿苹果相册)