Skip to content

Commit 0b808ac

Browse files
committed
Fix notification crash
1 parent 30262b5 commit 0b808ac

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

Examples/ContentView.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,20 @@ struct ScrollViewLoaderTestApp: App {
1313

1414
struct ContentView: View {
1515

16+
17+
var body: some View {
18+
NavigationView {
19+
NavigationLink(destination: DetailsSearch()) {
20+
Text("Go to details")
21+
.padding()
22+
}
23+
}
24+
25+
26+
}
27+
}
28+
29+
struct DetailsSearch: View {
1630
@State var data: [Int] = Array(0..<1)
1731

1832
var body: some View {

Sources/ScrollViewLoader/ScrollViewLoader.swift

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ struct DelegateHolder<Content: View>: View {
2626
content
2727
.introspectScrollView { scrollView in
2828
scrollView.delegate = offsetNotifier
29-
scrollView.addObserver(offsetNotifier, forKeyPath: "contentSize", context: nil)
29+
offsetNotifier.scrollView = scrollView
3030
offsetNotifier.scrollViewDidScroll(scrollView)
3131
}
3232
}
@@ -38,14 +38,19 @@ class ScrollOffsetNotifier: NSObject, UIScrollViewDelegate, ObservableObject {
3838
private var canNotify = true
3939
private var trigger: OffsetTrigger
4040
private var oldContentHeight: Double = 0
41+
weak var scrollView: UIScrollView? {
42+
didSet {
43+
scrollView?.addObserver(self, forKeyPath: "contentSize", context: nil)
44+
}
45+
}
4146

4247
init(offsetTrigger: OffsetTrigger, onNotify: @escaping () async -> ()) {
4348
self.trigger = offsetTrigger
4449
self.onNotify = onNotify
4550
}
4651

4752
deinit {
48-
removeObserver(self, forKeyPath: "contentSize")
53+
scrollView?.removeObserver(self, forKeyPath: "contentSize")
4954
}
5055

5156
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {

0 commit comments

Comments
 (0)