self-sizing-in-UICollectionView

给出最接近的预估大小

设置estimatedItemSize,UICollectionView需要拿这个值去设置一个初始的contentSize,所以给一个最为接近的值,ios10中提供了一个UICollectionViewFlowLayoutAutomaticSize的常量,这个值可以在cell不断加载的过程中调整预估大小,使contentsize的大小越来越接近实际大小。

设置好cell的约束

UITableView不同的是,UICollectionView在设置约束时,需要给定cell横向的宽度,只有给定宽度值,才能让UICollectionViewCell基于这个宽度得出高度值,不然两个值都是不确定的,不能使self-sizing正确发挥作用。

约束的设置大致如下:

 UILabel * contentLabel = [UILabel new];
    [self.contentView addSubview:contentLabel];

    UILabel * titleLabel = [UILabel new];
    titleLabel.numberOfLines = 0;
    titleLabel.font = [UIFont systemFontOfSize:20.0];
    [self.contentView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.contentView).offset(10);
        make.left.equalTo(self.contentView);
        make.right.equalTo(self.contentView).offset(-10);
    }];
    self.titleLabel = titleLabel;

    self.contentView.backgroundColor = [UIColor redColor];
    contentLabel.textColor = [UIColor blackColor];
    contentLabel.font = [UIFont systemFontOfSize:15.0];
    contentLabel.numberOfLines = 0;
    contentLabel.backgroundColor = [UIColor greenColor];

    //ios8中可以给定宽度为CGRectGetWidth([UIScreen mainScreen].bounds) - 21
    self.contentLabel = contentLabel;
    [contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_baseline).offset(10);
        make.left.equalTo(self.contentView).offset(10);
        make.right.equalTo(self.contentView).offset(-10);
        make.bottom.equalTo(self.contentView).offset(-10);
        make.width.equalTo(@(CGRectGetWidth([UIScreen mainScreen].bounds) - 20));
    }];

iOS8中出现的问题

在iOS8中发现一个bug,当cellwidthUICollectionViewwidth相同时,UICollectionView就不能正常滚动了,应该是contentSize的计算出了问题,为了解决这个问题,我把cell的宽度较之UICollectionView给小了一个像素,但这样并没有从根本上解决问题。今后的实践中还应继续探索,究竟什么原因导致的这个bug

一个小插曲

如果设置约束时使用了UILabelbaseline为参照,注意当label中的文字是中文,并且显示的文字是具有行间距的富文本时,这个参照是有问题的。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值