UICollectionView的高度自适应

    xiaoxiao2021-04-16  38

    estimatedItemSize是iOS 8中苹果最新推出的黑魔法,可以让CollectionView中也能让 cell 自适应内容大小,达到自动适应高度的预期效果!

    UICollectionView的高度自适应的原理:

    1.CollectionView根据 layout 的 estimatedItemSize 算出估计的 contentSize,有了 contentSize CollectionView就开始显示

    2.CollectionView 在显示的过程中,即将被显示的 cell 根据 autolayout 的约束算出自适应内容的 size

    3.layout 从 CollectionView 里获取更新过的 size attribute

    4.layout 返回最终的 size attribute 给 CollectionView

    5.CollectionView 使用这个最终的 size attribute 展示 cell

    UICollectionView的高度自适应的实现:

    1. 设置 estimatdItemSize

    设置 UICollectionViewFlowLayout 的 estimatdItemSize 的预估高度

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

    layout.estimatedItemSize = CGSizeMake([[UIScreen mainScreen] bounds].size.width, 200);

    estimatdItemSize 的默认值为 CGSizeZero ,所以要给一个非0值开启高度估算。

    2.对cell 进行约束添加

    #import"LastCell.h"

    #import"Masonry.h"

    @implementationLastCell

    -(instancetype)initWithFrame:(CGRect)frame{

    self= [super initWithFrame: frame];

    if(self) {

    self.backgroundColor= [UIColor whiteColor];

    self.testLabel= [UILabel new];

    [self.contentView addSubview: self.testLabel];

    self.testImage= [UIImageView new];

    [self.contentView addSubview: self.testImage];

    self.testLabel.numberOfLines=0;

    self.testImage.backgroundColor= [UIColor redColor];

    self.testLabel.backgroundColor= [UIColor purpleColor];

    [self creatAutoLayout];

    }

    returnself;

    }

    - (void)creatAutoLayout{

    [self.contentView mas_makeConstraints:^(MASConstraintMaker*make) {

    make.left.top.mas_equalTo(0);

    make.width.mas_equalTo(300);

    make.bottom.mas_equalTo(self.testLabel.mas_bottom).offset(12.0);

    }];

    [self.testImage mas_makeConstraints:^(MASConstraintMaker*make) {

    make.left.width.top.mas_equalTo(self.contentView);

    make.height.mas_equalTo(150);

    }];

    [self.testLabel mas_makeConstraints:^(MASConstraintMaker*make) {

    make.top.mas_equalTo(self.testImage.mas_bottom).offset(10.0);

    make.left.width.mas_equalTo(self.testImage);

    }];

    }

    - (UICollectionViewLayoutAttributes*)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes*)layoutAttributes {

    [self setNeedsLayout];

    [self layoutIfNeeded];

    CGSize size = [self.contentView systemLayoutSizeFittingSize: layoutAttributes.size];

    CGRect cellFrame = layoutAttributes.frame;

    cellFrame.size.height= size.height;

    layoutAttributes.frame= cellFrame;

    return layoutAttributes;

    }

    @end

    demo 传送门:https://github.com/lingbing0/TestLayout

    转载请注明原文地址: https://ju.6miu.com/read-672971.html

    最新回复(0)