-
Notifications
You must be signed in to change notification settings - Fork 364
Listen ScrollView contentOffset
and set it
#54
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
In iOS 14 you can use: ScrollViewReader to set the content offset. In iOS 14 for listening to the import SwiftUI
import Introspect
import Combine
struct ScrollViewDidScrollViewModifier: ViewModifier {
class ViewModel: ObservableObject {
var contentOffsetSubscription: AnyCancellable?
}
@StateObject var viewModel = ViewModel()
var didScroll: (CGPoint) -> Void
func body(content: Content) -> some View {
content
.introspectScrollView { scrollView in
if viewModel.contentOffsetSubscription == nil {
viewModel.contentOffsetSubscription = scrollView.publisher(for: \.contentOffset)
.sink { contentOffset in
didScroll(contentOffset)
}
}
}
}
}
extension ScrollView {
func didScroll(_ didScroll: @escaping (CGPoint) -> Void) -> some View {
self.modifier(ScrollViewDidScrollViewModifier(didScroll: didScroll))
}
}
struct ContentView: View {
var body: some View {
ScrollView {
ForEach(1..<21) { _ in
Text("Hello, world!")
.padding()
}
}
.didScroll { contentOffset in
print(contentOffset)
}
}
} |
This is not an Introspect Issue, but @lucastimeless has also provided a nice solution. That said I will close this issue. |
Please be careful with this solution, as sinking the publisher within the view creates a retain and your view (and related viewmodels) will not be de-allocated. Here's the fix:
|
@lucastimeless thanks for the answer! However it keeps publishing values and the CPU usage is at 100% - is there a way to only listen to value changes? |
hi there, I'm late for the party. As title, can we using this library to do something like this? Listen ScrollView
contentOffset
and set it. Sorry if I asking question at wrong place.The text was updated successfully, but these errors were encountered: