美文网首页iOS 开发记录
iOS UICollectionView autolayout

iOS UICollectionView autolayout

作者: 拇指猿 | 来源:发表于2019-06-29 12:50 被阅读0次

    iOS UICollectionView autolayout UICollectionViewCell 瀑布流加载网络图片自适应cell的高度章

    • 这篇文章主要是用来给自己做记录,防止以后忘掉

    • 效果图

    image

    瀑布流

    • 网上有很多iOS的瀑布流的资料,这里只记录UICollectionViewCell内部约束布局并且加载网络图片让Cell的高度可以自适应显示瀑布流的效果。

    • 瀑布流的一般就是派生UICollectionViewFlowLayout

    • 重写UICollectionViewFlowLayout的prepareLayout方法,一次性计算所有item的frame,并创建item对应的UICollectionViewLayoutAttributes用一个数组把UICollectionViewLayoutAttributes存储起来返回。

    • 重写layoutAttributesForElementsInRect方法,返回prepareLayout中item创建的UICollectionViewLayoutAttributes数组。

    
    @interface MSPinterestFlowLayout : UICollectionViewFlowLayout
    
    @property (nonatomic, assign) CGFloat itemWidth;
    
    @property (nonatomic, assign) NSInteger columnCount;
    
    @end
    
    
    
    @interface MSPinterestFlowLayout ()
    
    @property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *layoutAttributes;
    
    @property (nonatomic, strong) NSArray<NSNumber *> *heightsForColumnArray;
    
    @end
    
    @implementation MSPinterestFlowLayout
    
    - (void)prepareLayout
    
    {
    
        [super prepareLayout];
    
        [_layoutAttributes removeAllObjects];
    
        NSInteger column = self.columnCount;
    
        NSInteger section = 0;
    
        NSInteger numberOfItem = [self.collectionView numberOfItemsInSection:section];
    
        NSMutableArray<NSNumber *> *allColumnMaxY = [NSMutableArray array];
    
        for (int currentColumn = 0; currentColumn < column; currentColumn++)
    
        {
    
            allColumnMaxY[currentColumn] = @(0);
    
        }
    
        for (int index = 0; index < numberOfItem; index++)
    
        {
    
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:section];
    
            CGFloat minColumnMaxY = allColumnMaxY[0].floatValue;
    
            NSInteger itemColumn = 0;
    
            for (int columnIndex = 0; columnIndex < column; columnIndex++)
    
            {
    
                CGFloat columnMaxyValue = allColumnMaxY[columnIndex].floatValue;
    
                if (minColumnMaxY > columnMaxyValue)
    
                {
    
                    minColumnMaxY = columnMaxyValue;
    
                    itemColumn = columnIndex;
    
                }
    
            }
    
            // 这里获取item的UICollectionViewLayoutAttributes布局属性,如果是高度根据手动计算出来的,那么在下面直接设置item的高度就好。(网上看到大多都是能确定item高度的瀑布流布局方式)
    
            UICollectionViewLayoutAttributes *layoutAttributes = [self layoutAttributesForItemAtIndexPath:indexPath];
    
            CGRect frame = layoutAttributes.frame;
    
            CGSize size = frame.size;
    
            CGFloat itemY = minColumnMaxY + self.minimumLineSpacing;
    
            CGFloat itemX = self.sectionInset.left + (self.minimumInteritemSpacing + size.width) * itemColumn;
    
            CGRect itemRect = CGRectMake(itemX, itemY, size.width, size.height);
    
            layoutAttributes.frame = itemRect;
    
            [self.layoutAttributes addObject:layoutAttributes];
    
            allColumnMaxY[itemColumn] = @(CGRectGetMaxY(itemRect));
    
        }
    
        _heightsForColumnArray = allColumnMaxY;
    
    }
    
    - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
    
    {
    
        return self.layoutAttributes;
    
    }
    
    - (CGSize)collectionViewContentSize {
    
        CGSize size = [super collectionViewContentSize];
    
        if (_heightsForColumnArray.count == 0) {
    
            return size;
    
        }
    
        CGFloat height = _heightsForColumnArray[0].floatValue;
    
        for (int i = 0; i < _heightsForColumnArray.count; i++)
    
        {
    
            if (height < _heightsForColumnArray[i].floatValue)
    
            {
    
                height = _heightsForColumnArray[i].floatValue;
    
            }
    
        }
    
        return CGSizeMake(size.width, height + self.sectionInset.bottom);
    
    }
    
    #pragma mark - Getter
    
    - (NSMutableArray<UICollectionViewLayoutAttributes *> *)layoutAttributes
    
    {
    
        if (!_layoutAttributes)
    
        {
    
            _layoutAttributes = [NSMutableArray<UICollectionViewLayoutAttributes *> array];
    
        }
    
        return _layoutAttributes;
    
    }
    
    - (CGFloat)itemWidth
    
    {
    
        if (_itemWidth == 0)
    
        {
    
            NSInteger column = self.columnCount;
    
            CGFloat itemWidth = (CGRectGetWidth(self.collectionView.frame) - self.sectionInset.left - self.sectionInset.right - (column - 1) * self.minimumInteritemSpacing) / column;
    
            _itemWidth = itemWidth;
    
        }
    
        return _itemWidth;
    
    }
    
    @end
    
    

    约束布局的Cell item的高度获取。

    • 这边特别描述一下约束布局Cell的高度获取方法

    • 因为我想拿到cell约束布局的高度,所以必须是系统自动根据约束计算出来的高度。(主要是想偷懒,不想自己去手动计算cell子控件的各个高度)使用的是layoutAttributesForItemAtIndexPath方法可以在下面的代码中看到

    • 手动布局只需要根据indexPath创建UICollectionViewLayoutAttributes然后给frame进行一个赋值,更改item的位置进行瀑布流式的布局方式。

    
    // 这里获取item的UICollectionViewLayoutAttributes布局属性,如果是高度根据手动计算出来的,那么在下面直接设置item的高度就好。(网上看到大多都是能确定item高度的瀑布流布局方式)
    
            UICollectionViewLayoutAttributes *layoutAttributes = [self layoutAttributesForItemAtIndexPath:indexPath];
    
            CGRect frame = layoutAttributes.frame;
    
            CGSize size = frame.size;
    
            CGFloat itemY = minColumnMaxY + self.minimumLineSpacing;
    
            CGFloat itemX = self.sectionInset.left + (self.minimumInteritemSpacing + size.width) * itemColumn;
    
            CGRect itemRect = CGRectMake(itemX, itemY, size.width, size.height);
    
            layoutAttributes.frame = itemRect;
    
    

    根据网络图片cell的高度自适应

    • 也有其他的文章有讲到网络图片获取cell自适应高度,可以看看其他人的做法。

    • 如果是cell约束布局,那么宽度是确定的,我这边是根据图片的宽度进行约束cell的宽度。(不会的话,可以去看看相关的文章)

    • 因为图片一开始是不能确定高度的,开始我们使用一个默认的高度,并且我们只能知道item的宽度,所以图片宽度是确定的,所以图片下载下来是需要更新图片高度约束。

    • 使用SDWebImage加载网络图片

    
    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
        MSHomeCellModel *model = _models[indexPath.row];
    
        MSHomeCollectionViewCell *cell  = [collectionView dequeueReusableCellWithReuseIdentifier:_kCellIdentifier forIndexPath:indexPath];
    
        cell.imageHeight = 10;
    
        cell.width = ((MSPinterestFlowLayout *)collectionView.collectionViewLayout).itemWidth;
    
        cell.title = model.title;
    
        cell.avatarURL = model.avatarURL;
    
        cell.attentionNUmber = model.attentionNUmber;
    
        cell.nickname = model.nickname;
    
        cell.isAttention = model.isAttention;
    
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.imageURL] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
    
            if (model.isCalculateImageHeight)
    
            {
    
                cell.imageHeight = model.imageHeight;
    
            }else
    
            {
    
                CGFloat height = (image.size.height / image.size.width) * cell.width;
    
                cell.imageHeight = height;
    
                model.imageHeight = height;
    
                model.isCalculateImageHeight = YES;
    
                // 这个调用会让所有的item全部重新布局。
    
                [collectionView reloadItemsAtIndexPaths:@[indexPath]];
    
            }
    
        }];
    
        return cell;
    
    }
    
    

    cell布局

    • 最后放上cell布局的代码
    
    [self.contentView addSubview:self.imageView];
    
        [self.contentView addSubview:self.titleLabel];
    
        [self.contentView addSubview:self.avatarImageView];
    
        [self.contentView addSubview:self.nicknameLabel];
    
        [self.contentView addSubview:self.attentionButton];
    
        [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
    
            make.top.left.right.equalTo(@(0));
    
            make.height.greaterThanOrEqualTo(@(_kImageViewDefaultHeight));
    
        }];
    
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    
            make.top.equalTo(self.imageView.mas_bottom).offset(9);
    
            make.left.equalTo(@(10));
    
            make.right.lessThanOrEqualTo(@(-10));
    
        }];
    
        [_avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
    
            make.top.equalTo(self.titleLabel.mas_bottom).offset(17);
    
            make.left.equalTo(self.titleLabel);
    
            make.width.height.equalTo(@(20));
    
        }];
    
        [_nicknameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    
            make.left.equalTo(self.avatarImageView.mas_right).offset(4);
    
            make.right.lessThanOrEqualTo(@(-50));
    
            make.centerY.equalTo(self.avatarImageView);
    
        }];
    
        [_attentionButton mas_makeConstraints:^(MASConstraintMaker *make) {
    
            make.right.equalTo(@(-10));
    
            make.centerY.equalTo(self.nicknameLabel);
    
            make.bottom.equalTo(@(-15));
    
        }];
    
        [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
    
            make.top.left.right.equalTo(self.imageView);
    
            make.bottom.equalTo(self.attentionButton.mas_bottom).offset(15);
    
        }];
    
    
    • 外部告诉图片高度进行图片高度约束布局更新(更新时机是个问题,大量图片更新高度,cell需要重新布局,界面会存在跳动,并不友好。推荐大家还是尽量使用计算的结果进行cell的size,只需要把高度在flowLayout中存储就行)
    
    - (void)p_resetImageViewConstraints
    
    {
    
        CGFloat imageWidth = 50;
    
        CGFloat imageHeight = _kImageViewDefaultHeight;
    
        if (_width > 0) {
    
            imageWidth = _width;
    
        }
    
        if (_imageHeight > 0) {
    
            imageHeight = _imageHeight;
    
        }
    
        [_imageView mas_remakeConstraints:^(MASConstraintMaker *make) {
    
            make.top.left.equalTo(@(0));
    
            make.width.equalTo(@(imageWidth));
    
            make.height.equalTo(@(imageHeight));
    
        }];
    
    }
    
    

    相关文章

      网友评论

        本文标题:iOS UICollectionView autolayout

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