美文网首页
UICollectionView 瀑布流 2022-02-12

UICollectionView 瀑布流 2022-02-12

作者: iOS打怪升级 | 来源:发表于2022-02-12 18:55 被阅读0次

1 原理

  • sizeForItemAtIndexPath 里面保存所有cell 的高度,用户后续手动计算实际cell y 值使用

  • cellForItemAtIndexPath 方法里面重新计算cell 的实际y 值:需要计算当前列的所有cell高度和,以及行间距和

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = UIColor.redColor;
    if (![cell.contentView viewWithTag:10]) {
        UILabel * label = [[UILabel alloc] init];
        label.text = [NSString stringWithFormat:@"%ld",indexPath.row];
        label.tag = 10;
        label.frame = CGRectMake(0, 0, 30, 20);
        [cell.contentView addSubview:label];
    }else{
        UILabel * label = [cell.contentView viewWithTag:10];
        label.text = [NSString stringWithFormat:@"%ld",indexPath.row];
    }
    
    if (indexPath.section == 1 && indexPath.row == 0) {
        //首页起始的cell y ,因为有header footer 的高度占位,所以这里可能需要判断,如果没有header footer 就是0
        self.y = cell.frame.origin.y;
    }
    
    //列数
    NSInteger count = 4;
    NSInteger marginIner = 10;//左右间距
    NSInteger spaceLine = 10;//行距
    //当前cell 在当前行中的序号0...count-1
    NSInteger remainder=indexPath.row%count;
    //当前cell 所在的行数
    NSInteger currentRow=indexPath.row/count;
   //计算cell 的x ,利用cell宽度 + 间距,这里也可以直接利用cell 本身的x ,看需要
    NSInteger widthCell = cell.frame.size.width;
    CGFloat positonX = widthCell*remainder+marginIner*(remainder+1);
//    positonX = cell.frame.origin.x;//test
   
    //当前列的所有间距和
    CGFloat positionY=(currentRow+1)*spaceLine + self.y;
    //原理累计每一列的cell 高度 ,注意需要加上间距
    for (NSInteger i=0; i<currentRow; i++) {
        NSInteger position=remainder+i*count;
        //当前列的所有cell 高度和
        positionY+=[self.heightArr[position] floatValue];
    }
    //当前cell 的高度
    CGFloat   currentHeight=[self.heightArr[indexPath.row] floatValue];
    cell.frame = CGRectMake(positonX, positionY,widthCell,currentHeight) ;
    
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height=100+(arc4random()%100);
//保存所有的cell 高度
    [_heightArr addObject:@(height)];
//    return CGSizeMake((self.view.bounds.size.width-2)/3, 150);
    return CGSizeMake((self.view.bounds.size.width-50)/4, height);
}

相关文章

网友评论

      本文标题:UICollectionView 瀑布流 2022-02-12

      本文链接:https://www.haomeiwen.com/subject/kvcxlrtx.html