设置 estimatdItemSize
设置 layout 的 estimatdItemSize 预估高度
layout.estimatedItemSize = CGSizeMake(itemWidth, itemHeight);
默认值为 CGSizeZero ,给一个非0值开启高度估算。
给 cell 添加约束
如果想要 cell 高度自适应,一定要给清楚 cell 宽度的约束;如果想要宽度自适应,给定高度约束。
注意:如果使用的 IB, 不要在 xib 或者 Storyboard 给控件添加约束,因为这样添加上 top 和 left 会直接添加到 cell 上,而不是cell.contentView 上。同时还需要把 xib File’s owner 的 Use Auto Layout 给禁用掉。
1 | WS(ws); |
注意: 高度自适应,必须给定 contentView 的宽度。
top 和 bottom 约束一定要设定,并且注意 contentView.bottom = descLabel.bottom 是给 contentView 添加约束。
重写 preferredLayoutAttributesFittingAttributes 方法
在该方法内部,获取 contentView 自适应的 size。更改 attributes.frame 后返回。
1 | - (UICollectionViewLayoutAttributes *)preferredLayoutAttributesFittingAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes { |