How to recognise 2 Drag Gestures simultaneously in SwiftUI

114 Views Asked by At

I want to recognise two drag gestures at the same time so I can respond to 2-finger pan and magnification gestures.

struct GestureTest: View {
    @State var debug1 = ""
    @State var debug2 = ""
    
    var testGesture1: some Gesture {
        DragGesture(minimumDistance: 0.0)
            .onChanged { drag in
                debug1 = "test1: \(drag.location.debugDescription)"
            }
    }
    
    var testGesture2: some Gesture {
        DragGesture(minimumDistance: 0.0)
            .onChanged { drag in
                debug2 = "test2: \(drag.location.debugDescription)"
            }
    }
    
    var body: some View {
        Text(debug1)
        Text(debug2)
        Color.red
            .gesture(testGesture1)
            .gesture(testGesture2)
        Color.blue
            .gesture(testGesture1.simultaneously(with: testGesture2))
    }
}

I've tried using 2 independent gestures as shown in Color.red, as well as using the .simultaneousGesture(_:) modifier as shown in Color.blue. Neither of these approaches work. I've also tried using 1 MagnifyGesture but the MagnifyGesture.Value doesn't have anything to detect a pan gesture.

Is there any way to detect two drag gestures at the same time so I can respond to a 2-finger pan gesture as well as a magnification gesture?

1

There are 1 best solutions below

1
Pierre Janineh On

Use MagnifyGesture:

// Magnification Gesture
var magnify: some Gesture {
    MagnifyGesture()
        .onChanged { value in
            debug2 = "Magnify: \(value)"
        }
}