From 6aa09da464b7693edf207920193f378b2287a355 Mon Sep 17 00:00:00 2001 From: Matt Bruce Date: Mon, 11 Mar 2024 13:51:19 -0500 Subject: [PATCH] refactored to have a public contentSize publisher Signed-off-by: Matt Bruce --- VDS/Classes/SelfSizingCollectionView.swift | 26 +++++++++++++--------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/VDS/Classes/SelfSizingCollectionView.swift b/VDS/Classes/SelfSizingCollectionView.swift index d8656490..6f4de7d0 100644 --- a/VDS/Classes/SelfSizingCollectionView.swift +++ b/VDS/Classes/SelfSizingCollectionView.swift @@ -36,7 +36,15 @@ public final class SelfSizingCollectionView: UICollectionView { //-------------------------------------------------- private var collectionViewHeight: NSLayoutConstraint? private var anyCancellable: AnyCancellable? - + private var contentSizeSubject = CurrentValueSubject(.zero) + + //-------------------------------------------------- + // MARK: - Public Properties + //-------------------------------------------------- + public var contentSizePublisher: AnyPublisher { + contentSizeSubject.eraseToAnyPublisher() + } + //-------------------------------------------------- // MARK: - Overrides //-------------------------------------------------- @@ -67,17 +75,13 @@ public final class SelfSizingCollectionView: UICollectionView { setContentCompressionResistancePriority(.required, for: .vertical) collectionViewHeight = heightAnchor.constraint(equalToConstant: 0).activate() - anyCancellable = self.publisher(for: \.contentSize, options: [.old, .new]) - .scan((old: CGSize.zero, new: CGSize.zero)) { accumulator, newValue in - // accumulator.old contains the old contentSize value - // accumulator.new contains the new contentSize value before the current update - // newValue is the current update to contentSize - return (old: accumulator.new, new: newValue) - } + anyCancellable = self.publisher(for: \.contentSize, options: [.new]) .sink { [weak self] compare in - if compare.old != compare.new { - self?.invalidateIntrinsicContentSize() - self?.collectionViewHeight?.constant = compare.new.height + guard let self else { return } + if compare.height != self.collectionViewHeight?.constant { + self.invalidateIntrinsicContentSize() + self.collectionViewHeight?.constant = compare.height + self.contentSizeSubject.send(compare) } } }