self-sizing-in-UICollectionView

来源:互联网 发布:mcgs组态软件 编辑:程序博客网 时间:2024/05/20 22:27

给出最接近的预估大小

设置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中的文字是中文,并且显示的文字是具有行间距的富文本时,这个参照是有问题的。

0 0