解决collectionViewContentSize 首次计算不准确问题

·  阅读 1146

现在有这么一个场景,我tabelViewCell里面嵌套了uicollectionView,但是uicollectionView的高度是不确定的,我利用自动布局计算UITabelViewCell的高度,UITabelViewCell内部高度由UICcollectionView撑开。但是发现每次刚进来的时候计算有误差,后来发现collectionViewContentSize这哥size是不准确的。宽度比我计算的小,所以高度计算不准。解决方法:

self.collectionView.collectionViewLayout.invalidateLayout()

self.collectionView.reloadData()

self.collectionView.setNeedsLayout()

self.collectionView.layoutIfNeeded()

let h = self.collectionView.collectionViewLayout.collectionViewContentSize.height

self.h = h

self.collectionView.snp.updateConstraints { make in

make.height.equalTo(h)

}

或者

override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {

let size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)

self.collectionView.layoutIfNeeded()

let height = self.collectionView.collectionViewLayout.collectionViewContentSize.height

return CGSize(width: size.width,height: size.height + height)

        }

分类:
iOS
标签:
分类:
iOS
标签:
收藏成功!
已添加到「」, 点击更改