UICollectionView: 1>UICollectionViewFlowLayout流式布局

环境

XCode:Ver 7.2

DevelopeTarget: 9.2

UICollectionViewFlowlayout CollectionView流式布局

========================================================================================================

UICollectionView 使用时需要设置的点:

0> 数据源准备

- (void)viewDidLoad {
    [super viewDidLoad];

    _headerTitleDataSource = @[@"Section 1",@"Section 2",@"Section 3"];
    _collectionCellTitleDataSource = @[@[@"1-1",@"1-2",@"1-3"],
                                       @[@"2-1",@"2-2",@"2-3",@"2-4"],
                                       @[@"3-1",@"3-2",@"3-3"]];

    [self.testCollectionView setCollectionViewLayout:self.flowLayout animated:NO];
}

- (UICollectionViewFlowLayout *)flowLayout
{
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
        [_flowLayout setItemSize:CGSizeMake(200, 100)];// 设置每个cell的大小
        [_flowLayout setMinimumInteritemSpacing:100.0f];// 水平方向相邻两个cell的最小距离
        [_flowLayout setMinimumLineSpacing:50.0f]; // 垂直方向相邻两个cell的最小距离
        [_flowLayout setHeaderReferenceSize:CGSizeMake(50, 100)];//设置高度。ps:宽度无论如何设置都是CollectionView的宽度,原因目前不明。
    }
    return _flowLayout;
}

1> 设置Section 个数

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
        return [_headerTitleDataSource count];
}

2> 设置每个Section中Item个数

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:  (NSInteger)section
{
    return [_collectionCellTitleDataSource[section] count];
}

3> 设置每个CollectionCell

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];
    UILabel *textLabel = [cell viewWithTag:1000];
    textLabel.text = _collectionCellTitleDataSource[indexPath.section][indexPath.row];

    //设置border容易看清楚每个cell
    textLabel.layer.borderColor = [UIColor blackColor].CGColor;
    textLabel.layer.borderWidth = 1.0f;
    textLabel.layer.cornerRadius = 3.0f;

    return cell;
}

4> 设置 HeaderView and FooterView

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
   UICollectionReusableView *reusableView = nil;
    if (kind == UICollectionElementKindSectionHeader) {
        reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reuseableHeaderView" forIndexPath:indexPath];
        reusableView.backgroundColor = [UIColor greenColor];
        UILabel *titleLabel = [reusableView viewWithTag:2000];
        titleLabel.text = _headerTitleDataSource[indexPath.section];
    }
    return reusableView;
}

效果图:

UICollectionView: 1>UICollectionViewFlowLayout流式布局_第1张图片

上面就是CollectionView的比较常见的流式布局。从左到右,从上到下挨个排,地方不够就换行。

你可能感兴趣的:(Object-C)