您的位置:首页 > 产品设计 > UI/UE

UICollectionView的布局

2015-10-09 23:31 393 查看
UICollectionViewLayout决定UICollectionView的显示风格和每个UICollectionViewCell的尺寸、排布等。

如何自定义布局?

继承自
UICollectionViewFlowLayout
类(最根本的布局)

继承自
UICollectionViewLayout
类(流水布局)

重点讲解:
UICollectionViewLayoutAttributes


每个UICollectionViewCell都有自己的
UICollectionViewLayoutAttributes


一.继承自
UICollectionViewFlowLayout
类,重写父类的方法来定制UICollectionViewFlowLayout

//只要显示的边界发生改变就会重新布局:内部重新调用layoutAttributesForElementsInRect方法获取所有cell的布局属性

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

//Elements:UICollectionViewCell
//rect指的的UICollectionView的尺寸,即我们可视化的尺寸
//该方法返回的是Cells的Attributes

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

return [super layoutAttributesForElementsInRect:rect];
//在这里对cell进行自定义
}

//一些初始化的工作最好在这里实现
-(void)prepareLayout{
[super prepareLayout];
}


二.继承自
UICollectionViewLayout


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

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

NSMutableArray* array=[NSMutableArray array];
NSInteger count=[self.collectionView numberOfItemsInSection:0];
for(int i=0;i<count;i++){

UICollectionViewLayoutAttributes* attrs=[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
//这里设置利用attrs设置属性
[array addObject:attrs];
}

return array;
}

//设置指定的UICollectionViewCell可以调用这个方法
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: