iOS瀑布流的实现原理

为何我会对瀑布流为这么上进,非要将瀑布流来一次大清洗,非逼得自己将它彻底弄清楚。原因其实也很简单:之前刚出来找工作那会,每次面试官问到“解释一下瀑布流的实现”的时候,我都回答的支支吾吾,所以一直都对瀑布流耿耿于怀。今天刚好有些时间,就将瀑布流彻底的理解一遍,顺便记录一下学习笔记,以备不时之需。

为了具有大众性,在此我就以最常见的UICollectionView为例:                           

 @interface CollectionViewController : UICollectionViewController

@end

在CollectionViewController.m文件中

类似UITableViewController ,实现相关的协议方法

#pragma mark- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {return 1;}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

return self.allImages.count;}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

Cell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

cell.bgImageView.image = [UIImage imageNamed:self.allImages[indexPath.item]];

return cell;

}

创建CollectionViewController对象时,使用自己自定义的布局方式

在自定义的布局CustomLayout类中,进行自己想要的布局。

最后的效果是:


总结 : 瀑布流最重要的一步就是:在自己自定义布局的类中,通过计算每一张图片的摆放位置的大小,使得形成瀑布流的效果。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容