Fawzi Rifai
Fawzi Rifai

Reputation: 771

Drag gesture only if I start dragging on top of the view that I want to be dragged

I want a view to be dragged only if I start dragging on that view. Currently, if I start dragging from anywhere on the screen and then dragged over it, it drags.

import SwiftUI

struct ContentView: View {
    @State private var offset = CGSize.zero
    var body: some View {
        Text("Hello, world!")
            .offset(offset)
            .gesture(
                DragGesture()
                    .onChanged { gesture in
                        offset = gesture.translation
                    }
                    .onEnded { _ in
                        offset = CGSize.zero
                    }
            )
    }
}

Upvotes: 0

Views: 830

Answers (1)

Yrb
Yrb

Reputation: 9755

Here is a possible solution. Place a view behind the view you want draggable, such as a Color. Place a DragGesture on that to capture the drag if you miss the view you actually want draggable. This has to be a view that will be shown on screen, or this doesn't work, i.e. you can't use Color.clear.

struct ContentView: View {
    @State private var offset = CGSize.zero
    var body: some View {
        ZStack {
            // Place a Color behind your view, set to the background color.
            // It can't be clear as that doesn't work.
            Color.white
                // Place a DragGesture there to capture the drag if not on the view you want
                .gesture(DragGesture())
        Text("Hello, world!")
            .offset(offset)
            .gesture(
                DragGesture()
                    .onChanged { gesture in
                        offset = gesture.translation
                    }
                    .onEnded { _ in
                        offset = CGSize.zero
                    }
            )
        }
    }
}

Upvotes: 2

Related Questions