refactor code for possible memory issue

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
Matt Bruce 2024-05-01 09:36:57 -05:00
parent 9020cc3513
commit d109db6701

View File

@ -23,12 +23,12 @@ public final class SelfSizingCollectionView: UICollectionView {
/// - layout: Layout used for this CollectionView /// - layout: Layout used for this CollectionView
public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout) super.init(frame: frame, collectionViewLayout: layout)
self.setupContentSizeObservation() self.initialSetup()
} }
public required init?(coder: NSCoder) { public required init?(coder: NSCoder) {
super.init(coder: coder) super.init(coder: coder)
self.setupContentSizeObservation() self.initialSetup()
} }
//-------------------------------------------------- //--------------------------------------------------
@ -69,22 +69,31 @@ public final class SelfSizingCollectionView: UICollectionView {
//-------------------------------------------------- //--------------------------------------------------
// MARK: - Private Methods // MARK: - Private Methods
//-------------------------------------------------- //--------------------------------------------------
private func setupContentSizeObservation() { private func initialSetup() {
//ensure this hasn't run before
guard anyCancellable == nil else { return }
//ensure autoLayout uses intrinsic height //ensure autoLayout uses intrinsic height
setContentHuggingPriority(.required, for: .vertical) setContentHuggingPriority(.required, for: .vertical)
setContentCompressionResistancePriority(.required, for: .vertical) setContentCompressionResistancePriority(.required, for: .vertical)
collectionViewHeight = height(constant: 0, priority: .defaultHigh) collectionViewHeight = height(constant: 0, priority: .defaultHigh)
anyCancellable = self.publisher(for: \.contentSize, options: [.new]) anyCancellable = self.publisher(for: \.contentSize, options: [.new, .old])
.sink { [weak self] compare in .sink { [weak self] compare in
guard let self else { return }
if compare.height != self.collectionViewHeight?.constant { guard let self,
self.invalidateIntrinsicContentSize() let currentHeight = self.collectionViewHeight?.constant,
self.collectionViewHeight?.constant = compare.height compare.height != currentHeight else { return }
self.contentSizeSubject.send(compare)
} self.invalidateIntrinsicContentSize()
self.collectionViewHeight?.constant = compare.height
self.contentSizeSubject.send(compare)
} }
} }
deinit {
anyCancellable?.cancel()
}
} }
extension UITraitCollection { extension UITraitCollection {