diff --git a/VDS/Classes/SelfSizingCollectionView.swift b/VDS/Classes/SelfSizingCollectionView.swift index ad5d5661..ff1f9cb8 100644 --- a/VDS/Classes/SelfSizingCollectionView.swift +++ b/VDS/Classes/SelfSizingCollectionView.swift @@ -23,12 +23,12 @@ public final class SelfSizingCollectionView: UICollectionView { /// - layout: Layout used for this CollectionView public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) { super.init(frame: frame, collectionViewLayout: layout) - self.setupContentSizeObservation() + self.initialSetup() } public required init?(coder: NSCoder) { super.init(coder: coder) - self.setupContentSizeObservation() + self.initialSetup() } //-------------------------------------------------- @@ -69,22 +69,31 @@ public final class SelfSizingCollectionView: UICollectionView { //-------------------------------------------------- // 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 setContentHuggingPriority(.required, for: .vertical) setContentCompressionResistancePriority(.required, for: .vertical) 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 - guard let self else { return } - if compare.height != self.collectionViewHeight?.constant { - self.invalidateIntrinsicContentSize() - self.collectionViewHeight?.constant = compare.height - self.contentSizeSubject.send(compare) - } + + guard let self, + let currentHeight = self.collectionViewHeight?.constant, + compare.height != currentHeight else { return } + + self.invalidateIntrinsicContentSize() + self.collectionViewHeight?.constant = compare.height + self.contentSizeSubject.send(compare) } } + + deinit { + anyCancellable?.cancel() + } } extension UITraitCollection {