How to detect drag events for the stack when drag action have started outside of the stack view?
On the screen are placed the main stack/view (GREEN) and sub-stack/view (RED). I need to implement functionality which detects swipe/drag interaction for the GREEN view. Here are two scenarios and the second is failing:
How to detect drag events when drag have started outside of the stack view?
I have tried many things over the week. Some of them are:
- I have tried setting coordinate space for drag coordinates, and some views.
- Tried adding multiple simultaneous gesture recognizers.
Sample code which can be added to Xcode Playgrounds or demo app.
import PlaygroundSupport
import SwiftUI
PlaygroundPage.current.needsIndefiniteExecution = true
struct DemoView: View {
var body: some View {
VStack {
VStack {
Text("3")
}
.id("RED")
.frame(width: 200, height: 300, alignment: .center)
.background(.red)
.simultaneousGesture(
DragGesture()
.onChanged({
print("🔴", $0.location)
})
)
}
.id("GREEN")
.frame(width: 400, height: 700, alignment: .center)
.background(.green)
.simultaneousGesture(
DragGesture()
.onChanged({
print("🟢", $0.location)
})
)
}
}
// Write grean rectangle
let view = DemoView()
PlaygroundPage.current.setLiveView(view)
2
Answers
Using an overlay in this version it detects red drag [exclusively] if you start in red and green [also exclusively] if you start in green.
So if I comment out the green gesture and use the coordinates returned, I can use the coordinates returned to work out if I am in red or green within the "red" drag gesture.
Of course, if you start within the green, nothing is reported. But start within the red, and you get both.
You can now uncomment the green gesture and use the same sort of logic, within its gesture.
And there you have it; if you start on green it will work and if you start on red it will work.