I am trying to find out when the user interacts with a horizontal ScrollView in SwiftUI. The problem is that most solutions that I have found are based around when the scroll view moves. This doesn't work as the scroll view also moves without the user actually moving it. This example should show what I am essentially trying to do with my app:
import SwiftUI
import UIKit
struct ContentView: View {
@State var colors: [Color] = [Color.orange, Color.blue, Color.green, Color.pink]
@State var target = 0
var body: some View {
VStack {
ScrollViewReader { value in
ScrollView(.horizontal) {
HStack(spacing: 20) {
ForEach(0..<100) { i in
Rectangle().fill(colors[i % colors.count]).frame(width: 350, height: 350)
.id(i)
}
}
}
HStack {
Button("Up") {
target += 1
withAnimation(){
value.scrollTo(target, anchor: .center)
}
}
Spacer()
Button("Down") {
target -= 1
withAnimation(){
value.scrollTo(target, anchor: .center)
}
}
}
.padding()
}
}
}
}
I'm trying to get the app to tell me when the user is moving the scroll view vs when "the app" moves the scroll view (as shown through the up and down buttons).
When I try and use Drag Gestures they lock the scroll view, even with a Tap Gesture before it. Changing the minimumDistance will make only one of the actions fire, either the gesture or the scroll view, and not simultaneously.
.onTapGesture { }
.simultaneousGesture(
DragGesture(minimumDistance: 0)
.onChanged { _ in
print("moving")
}
.onEnded { _ in
print("stopped")
})
And something like this
doesn't work as when the scroll view moves programmatically it would be detected as the user moving it.
How can I get the app to know whether the scroll view is being moved by the user and when it is being moved programmatically?