AutosizedCollectionView
class AutosizedCollectionView: UICollectionView {
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
registerObserver()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
registerObserver()
}
deinit {
unregisterObserver()
}
public override var intrinsicContentSize: CGSize {
return contentSize
}
//public override var intrinsicContentSize: CGSize {
// return CGSize(width: UIView.noIntrinsicMetric, height: contentHeight())
//}
private func registerObserver() {
addObserver(self, forKeyPath: #keyPath(UICollectionView.contentSize), options: [], context: nil)
}
private func unregisterObserver() {
removeObserver(self, forKeyPath: #keyPath(UICollectionView.contentSize))
}
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(UICollectionView.contentSize) {
//check, and update superview height constraint ...
invalidateIntrinsicContentSize()
}
}
}