这几天调整UI,重新看了下UICollectionView的东西,才发觉它真的非常强大,很有必要好好总结下。
UICollectionView和UITableView很相似,但它要更加强大,可以说是青出于蓝而胜于蓝。
UITableView的布局形式比较单一,局限于行列表,而UICollectionView的强大之处在于把视图布局分离出来成为一个独立的类,你想实现怎样的视图布局,就子类化这个类并在其中实现。
UICollectionView基础
- UICollectionViewFlowLayout:视图布局对象(流视图:一行排满,自动排到下行),继承自UICollectionViewLayout。
UICollectionViewLayout有个collectionView属性,
所有的视图布局对象都继承自UICollectionViewLayout。若我们要自定义布局对象,我们一般继承UICollectionViewFlowLayout就可以了。 - 需要实现三个协议;UICollectionViewDataSource(数据源)、UICollectionViewDelegateFlowLayout(视图布局)、UICollectionViewDelegate。
可以看得出,除了视图布局,UICollectionView几乎和UITableView一样,但这也正是它的强大之处。
初始化
self.flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal; // 默认为竖向
self.flowLayout.minimumLineSpacing = 5.0; // 竖向时为最小行间距,横向时为最小列间距
self.flowLayout.minimumInteritemSpacing = 5.0; // 竖向时为最小列间距,横向时一般没用
self.flowLayout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15); // 边距
self.horCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.flowLayout];
self.horCollectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.horCollectionView.backgroundColor = LVDColor_bg;
self.horCollectionView.delegate = self;
self.horCollectionView.dataSource = self;
[self.collectionView registerClass:[clazz class] forCellWithReuseIdentifier: cellId];
if (@available(iOS 11.0, *)) {
self.horCollectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
} else {
self.horCollectionView.alwaysBounceHorizontal = YES;
}
[self.view addSubview:_collectionView];
// 注册cell、sectionHeader、sectionFooter
[self.horCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cellId];
[self.horCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
[self.horCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerId];