1.对于动态高度更新
你可以为collectionView的contentSize添加一个观察者
collectionView.addObserver(self, forKeyPath: "contentSize", options: [.new,.old], context: nil)
然后你可以重写这个方法来检查collectionView中contentSize的变化
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?) {
if let obj = object as? UICollectionView, obj == self.collectionView && keyPath == "contentSize" {
if let oldVal = change?[NSKeyValueChangeKey.oldKey] as? CGSize, let newValue = change?[NSKeyValueChangeKey.newKey] as? CGSize,oldVal.height == newValue.height {
return
}
let contentHeight = self.collectionView.contentSize.height
//You can update the height constraint or you can manually update the height of collection view.
self.heightConstraintCV.constant = contentHeight
}
UIView.animate(withDuration: 0.1) {
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}
}
2。一个简单的方法是手动计算高度。如果您确定每行将有 5 个元素。
height = (numberOfRows * heightOfEachRow)
3.直接设置contentSizeHeight为collectionView的高度
height = collectionView.contentSize.height