1自定义布局的重要方法
1> collectionVIew将要显示时准备布局,每当布局更新时,调用该方法做布局前的准备
- (void)prepareLayout;
2> 创建指定索引的cell的布局属性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
3> 返回collectionView内所的视图的布局属性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;
4> 自定义布局时一定要实现此方法来返回collectionView的contentSize,内容尺寸,collectionView的滚动范围
- (CGSize)collectionViewContentSize
/** 计算cell的高 */
- (CGFloat)waterfallFlowLayout:(HMWaterfallFlowLayout *)flowLayout heightForCellWidth:(CGFloat)cellWidth indexPath:(NSIndexPath *)indexPath {
HMShop *shop = self.shopes[indexPath.item];
return shop.height / shop.width * cellWidth;
}
实现加载更多数据
// 当显示footerView显示时加载数据
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// 1> 如果当前footerView没有显示或正在加载数据时直接返回
if (self.footerView == nil || self.footerView.activityIndicator.isAnimating) {
return;
}
// 2> 当offset.y + collectionView的高 > footerView的Y时开始加载数据
if ((scrollView.contentOffset.y + scrollView.bounds.size.height) > self.footerView.frame.origin.y) {
// 让菊花转正
[self.footerView.activityIndicator startAnimating];
// 延时两秒去加载数据,模型网络
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 1.加载数据
[self loadData];
// 2.停止菊花
[self.footerView.activityIndicator stopAnimating];
// 3.加载完之后把属性赋为nil
self.footerView = nil;
// 4.刷新collectionView重新调用数据源方法和重新布局
[self.collectionView reloadData];
});
}
}
// 加载数据
- (void)loadData {
// 添加数据
[self.shopes addObjectsFromArray:[HMShop shopsWithIndex:((self.dataIndex % 3) + 1)]];
// 让数据索引加加
self.dataIndex++;
}
.扩展》实现横竖屏改变列数
// 当屏幕发生旋转的时候会调用此方法,
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
if (size.width > size.height) {
self.flowLayout.columensCount = 4;
} else {
self.flowLayout.columensCount = 2;
}
}