更具體的代碼見文末demo地址
效果圖

效果圖.gif
使用方式
可以通過pod導(dǎo)入,也可以下載demo后把LYWaterFlowLayout文件夾導(dǎo)入。
pod 'LYWaterFlowLayout', '~> 0.0.2'
如果pod repo update后還pod search不到,可以運(yùn)行如下命令清下緩存后應(yīng)該就可以了。
rm ~/Library/Caches/CocoaPods/search_index.json
在使用的控制器中,
遵守代理<UICollectionViewDelegate, UICollectionViewDataSource,LYWaterFlowLayoutDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *datas;
- (void)viewDidLoad{
[super viewDidLoad];
[self configData];
[self creatUI];
}
-(void)configData{
// 瀑布流假數(shù)據(jù)
self.datas = [NSMutableArray array];
for (int i = 0; i < 25; i++) {
LYItemModel *itemModel = [[LYItemModel alloc] init];
itemModel.title = [NSString stringWithFormat:@"測試標(biāo)題%d", i];
itemModel.itemSizeScale = i%3 + 0.5; // item比例
[self.datas addObject:itemModel];
}
}
-(void)creatUI{
LYWaterFlowLayout *layout = [[LYWaterFlowLayout alloc] init];
layout.columnMargin = 10;
layout.rowMargin = 10;
layout.columnCount = 3;
layout.endgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
layout.degelate = self;
self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
self.collectionView.backgroundColor = [UIColor whiteColor];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
[self.collectionView registerClass:[LYCollectionViewCell class] forCellWithReuseIdentifier:cellIndentifier];
[self.view addSubview:self.collectionView];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.datas.count;
}
-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
LYCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIndentifier forIndexPath:indexPath];
LYItemModel *itemModel = self.datas[indexPath.row];
cell.backgroundColor = [UIColor yellowColor];
cell.titleLable.text = itemModel.title;
return cell;
}
-(CGFloat)Flow:(LYWaterFlowLayout *)Flow heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath{
// width是根據(jù)列數(shù)和列間距計(jì)算好的item寬度,可以再根據(jù)item的比例來計(jì)算高度
LYItemModel *itemModel = self.datas[indexPath.row];
return width*itemModel.itemSizeScale;
}