iOS collectionView自适应高度estimatedItemSize

collectionView自适应高度 有两个点需要注意
1.设置layout的estimatedItemSize属性

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.estimatedItemSize = CGSizeMake((SCREEN_WIDTH-24), autoSize(150));

2.在cell中重新并实现preferredLayoutAttributesFittingAttributes:方法【这个方法经常被遗漏,这样算出来的宽高就会有问题】

-(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;
}
posted @ 2021-12-15 14:31  qqcc1388  阅读(1761)  评论(0编辑  收藏  举报