1. Для динамических обновлений c высоты
Вы можете добавить наблюдателя для contentSize of collectionView
collectionView.addObserver(self, forKeyPath: "contentSize", options: [.new,.old], context: nil)
Затем вы можете переопределить этот метод, чтобы проверить изменения contentSize в collectionView
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 непосредственно как высоту коллекции.
height = collectionView.contentSize.height