Skip to content

Instantly share code, notes, and snippets.

@huynguyencong
Created November 2, 2021 11:39
Show Gist options
  • Save huynguyencong/a583db70f93d0587c096a9ca2c7be310 to your computer and use it in GitHub Desktop.
Save huynguyencong/a583db70f93d0587c096a9ca2c7be310 to your computer and use it in GitHub Desktop.
A collection view that has intrinsic content size is its content size
class ContentSizeCollectionView: UICollectionView {
var contentSizeObservation: NSKeyValueObservation?
override var intrinsicContentSize: CGSize {
return shouldFullSize ? contentSizeWithInset : CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)
}
var shouldFullSize: Bool = true {
didSet {
invalidateIntrinsicContentSize()
}
}
private var contentSizeWithInset: CGSize {
let heightInset = contentInset.top + contentInset.bottom
let widthInset = contentInset.left + contentInset.right
return CGSize(width: contentSize.width + widthInset,
height: contentSize.height + heightInset)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
contentSizeObservation = observe(\.contentSize) { [unowned self] (_, _) in
self.invalidateIntrinsicContentSize()
}
}
override func willMove(toSuperview newSuperview: UIView?) {
if newSuperview == nil {
contentSizeObservation?.invalidate()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment