UICollectionLayout布局 —— UIKit之学习UICollectionView记录二《流水布局》
重点知识
一、 加载collectionView注意事项
1.创建collectionView,有两种方式 :一种是xib和一种是纯代码;设置代理和数据源,注册cell,配置流水布局的属性,如上、下、左、右间距及行间距和列间距。
2. 创建CollectionViewCell,实现collectionView代理和数据源方法。
3. 设置每个cell的尺寸。
4.cell出现时显示动画
二、 流水布局思路分析
三、精华代码
1、布局一
//1.配置collectionView self.automaticallyAdjustsScrollViewInsets = YES; //默认为No, [self.view setBackgroundColor:[UIColor yellowColor]]; [self.collectionView registerNib:[UINib nibWithNibName:@"STRNearPeopleCell" bundle:nil] forCellWithReuseIdentifier:nearPeopleCell]; NSLog(@"%@",self.dataList); [self.collectionView reloadData]; //2.显示动画及设置大小 和加载cell - (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{ STRNearPeopleCell *hotcell = (STRNearPeopleCell *)cell; [hotcell showAnamil]; } //流水布局,系统UICollectionViewLayout.h - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{ CGFloat outInset = self.collectionView.frame.size.width - 2 * kMargin; NSInteger count = outInset / kItemSizeW; NSInteger extraTotal = (NSInteger)(outInset - kMargin * (count - 1 )); CGFloat itemWH; if (extraTotal < count * kItemSizeW) { itemWH = extraTotal / count; } else { CGFloat extraWidth = extraTotal % kItemSizeW; itemWH = kItemSizeW + extraWidth / count; } return CGSizeMake(itemWH, itemWH + 25); } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ return self.dataList.count; } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: - (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ STRNearPeopleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:nearPeopleCell forIndexPath:indexPath]; return cell; } //3.设置cell - (void)awakeFromNib { [super awakeFromNib]; // Initialization code } //此外是模拟数据,真实的话把注释取消掉,用来控制显示动画的。 - (void)showAnamil { //x和y的最终值为1 // if (self.live.isShow) { //当有网络模型时,可以把isShow字段加进去 // return; // } self.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1); [UIView animateWithDuration:1 animations:^{ self.layer.transform = CATransform3DMakeScale(1, 1, 1); // self.live.show = YES; //如果已经显示过yes }]; }
2、布局二
//定义每个UICollectionView 的大小 - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { return CGSizeMake(([UIScreen mainScreen].bounds.size.width-64) /3 ,([UIScreen mainScreen].bounds.size.width-64) /3); } //定义每个UICollectionView 的 margin - (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section { return UIEdgeInsetsMake(20, 8, 20, 8); }
将来的自己,会感谢现在不放弃的自己!