Search code examples
swiftuigesturedrag

SwiftUI - Drag Gesture doesn't activate on HStack with Buttons in it


I have an HStack with buttons in it defined like this:

GeometryReader { proxy in
  HStack {
    Button("test")
      .frame(width: 100, height: 50)
    Button("test")
      .frame(width: 100, height: 50)
    Button("test")
      .frame(width: 100, height: 50)
  }
  .frame(width: proxy.size.width)
  .gesture(
    .onChanged { gesture in
    // do something here
    }
  )
}

As you can see, I am trying to perform some function when the HStack is dragged. This works if the user drags starting from an empty space in the HStack, however, if the drag starts from the button, the gesture is not activated. How can I fix this?


Solution

  • You can use a View with an onTapGesture instead of a button.

    Try something like this:

    @State private var count = 0 // To check if dragging works
    
    GeometryReader { proxy in
        HStack {
            Text("test")
                .onTapGesture { // The action gesture
                    //
                }
                .foregroundColor(.blue) // Colour it like the default button
            
            
            .frame(width: 100, height: 50)
            
            Text("\(count)")
        }
        .gesture(DragGesture(minimumDistance: 1) // The dragging gesture
            .onChanged { gesture in
                count += 1
            })
    }
    

    You could possibly also try and disabling the button when dragging and then enable when you're done dragging.

    Good luck!