'Conditionnaly activate Gesture in SwiftUI

I'm looking for a way to able/disable DragGesture or to pass conditionally pass the Gesture to MyView() in swiftUI according to @State private var isDraggable:Bool

Since MyView() has some parameters that are reset on Appear() and Disappear(), I can not just do

If isDraggable { MyView() }else{MyView().gesture() }

How DragGesture is implemented in my code

MyView().gesture(DragGesture(minimumDistance: 0) .onChanged { value in} )


Solution 1:[1]

You can use GestureMask and choose between gestures

you can have .all, .none, .subviews, or .gesture

.gesture in your case would be the DragGesture.

.subviews would allow any gestures inside MyView

.all is both the DragGesture AND any gestures inside MyView (this is the default)

import SwiftUI

struct ConditionalGestureView: View {
    @State var activeGestures: GestureMask = .subviews
    var body: some View {
        MyView()
            .gesture(DragGesture(), including: activeGestures)
    }
}

Change the activeGestures variable per your use case

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1