自定义UICollectionView布局

线性布局

上一节讲解了自定义布局的基本实现思路,这一节主要用自定义布局实现线性布局,,做一个简单的图片浏览器效果。

自定义布局类1. 自定义布局类: UICollectionViewFlowLayout@end2. 重新父类的方法2.1 准备布局/// 准备操作 一般在这里设置一些初始化参数- (void)prepareLayout{// 必须要调用父类(父类也有一些准备操作)[super prepareLayout];* 0.7;self.itemSize = CGSizeMake(width, width);self.scrollDirection = UICollectionViewScrollDirectionHorizontal;self.minimumLineSpacing = 20;- width) * 0.5;self.sectionInset = UIEdgeInsetsMake(0, inset, 0, inset);}2.2 返回collectionView上面所有元素(比如cell)的布局属性- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{NSArray *array = [super layoutAttributesForElementsInRect:rect];+ * 0.5;for (UICollectionViewLayoutAttributes *attrs in array){);;attrs.transform = CGAffineTransformMakeScale(scale, scale);}return array;}2.3 当uicollectionView的bounds发生改变时,是否要刷新布局/// 当uicollectionView的bounds发生改变时,是否要刷新布局- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{return YES;}2.4 返回collectionView最终的偏移量(最终的停留位置)- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{;// 计算可见区域的面积CGRect rect = CGRectMake(proposedContentOffset.x, proposedContentOffset.y, size.width, size.height);NSArray *array = [super layoutAttributesForElementsInRect:rect];* 0.5;// 标记 cell 的中点与 UICollectionView 中点最小的间距CGFloat minDetal = MAXFLOAT;for (UICollectionViewLayoutAttributes *attrs in array){if (ABS(minDetal) > ABS(centerX – attrs.center.x)){minDetal = attrs.center.x – centerX;}}return CGPointMake(proposedContentOffset.x + minDetal, proposedContentOffset.y);}3. 控制器使用布局3.1 导入头文件#import “CYLineLayout.h”3.2 实例化布局CYLineLayout *layout = [[CYLineLayout alloc]init]; // 线性布局UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:frame collectionViewLayout:layout];3.3 UICollectionView的数据源方法// ……

同生天地间,为何我不能。

自定义UICollectionView布局

相关文章:

你感兴趣的文章:

标签云: