Created
November 2, 2021 11:39
-
-
Save huynguyencong/a583db70f93d0587c096a9ca2c7be310 to your computer and use it in GitHub Desktop.
A collection view that has intrinsic content size is its content size
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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