下面是个collectionView的懒加载。

- (UICollectionView *)collectionView{

    if (!_collectionView) {

    //先要创建一个布局。然后把布局加到collectionView中去。当然我们也可以用方法进行布局而不创建这个layout。

        UICollectionViewFlowLayout * layout = [UICollectionViewFlowLayout new];

        layout.itemSize =CGSizeMake(50,50);

        layout.scrollDirection = UICollectionViewScrollDirectionVertical;

        layout.minimumInteritemSpacing = 20;

        layout.minimumLineSpacing =5;

        [layout setSectionInset:UIEdgeInsetsMake(5, 20, 5, 20)];

    //下面初始化collectionView,把上面的layout加进去。如果我们要调用方法来布局的话,layout位置直接导入一个         

         [UICollectionViewFlowLayout new]就行。

        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];

        [self.view addSubview:self.collectionView];//把自已加到父视图中

        _collectionView.backgroundColor = [UIColor whiteColor];//背景默认是黑的,改一下颜色。

  //下面顺便做了一下单元格的注册。我这里是自定义的单元格

        [self.collectionView registerClass:[ItemCollectionViewCell class] forCellWithReuseIdentifier:@"ItemCell"];

        _collectionView.delegate =self;//记得设置代理。

        _collectionView.dataSource =self;

  //下面是第三方。Masonry,布局超级方便,建议去github了解。

        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {

            make.edges.mas_equalTo(0);//仅一句话就设置好,非常方便。

        }];

    }

    return _collectionView;

 

}

 

*************************如果上面你没有设置layout的话可以调下方方法进行布局操作***************************

总的看起来直接写layout能少不少代码。当然,需要跟据实际情况进行调整。

 

 

/** section的上下左右边距 */

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{

    return UIEdgeInsetsMake(5, 20, 5, 20);

}

/** 最小行间距 */

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{

    return 5;

}

/** 最小列间距 */

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{

    return 20;

}

/** 每格cell 宽高 */

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    CGFloat width = (kWindowW - 5 * 20) / 4;

    CGFloat height = width + 17;

    return CGSizeMake(width, height);

}