I’m trying to implement a functionality similar to the horizontal cryptocurrency listing on the CoinGecko website(viewed on a mobile phone), where the scrollable content is controlled from a separate fixed-position part of the screen.
In my SwiftUI app I want the content within the right side’s ScrollView to scroll horizontally, while the left part remains static. Essentially, I’m aiming to enable scrolling across the entire screen, regardless of where the touch interaction starts. How can I achieve this effect where touching and dragging on the non-scrollable left part controls the scroll in the ScrollView on the right?
This needs to be done without using any third-party libraries.
Here’s the code:
struct ContentView: View {
@State private var offset = 0.0
var body: some View {
ZStack {
ZStack {
ScrollView(.horizontal) {
Rectangle()
.frame(width: 400)
.foregroundColor(.gray.opacity(0.7))
}
.padding(.leading, 150)
}
.offset(x: offset)
HStack {
ZStack {
Rectangle()
.fill(.white)
.frame(width: 150)
}
.gesture(
DragGesture(minimumDistance: 0)
.onChanged { val in
offset = val.translation.width
}
.onEnded { val in
offset = 0
}
)
Spacer()
}
}
}
}
#Preview {
ContentView()
}
I described above what I tried to do, but attempting to scroll the left part just moves the entire right part, whereas I need the content inside the ScrollView to move