UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to use both .draggable and .onTapGesture?

Forums > SwiftUI

I'm trying to build a menu of sorts, so I have a list of items that I want to be clickable (I'm targeting Mac OS for now). I also want them to be draggable so the order of the menu can be changed.

As soon as I add .draggable my .onTapGesture stops working. And I know that I can add multiple Gestures, but that only works with Gestures, and .draggable doesn't play nice with that as it is an abstraction on top of gestures.

One workaround that works and what I'm using now is to put my menu in a List, and enable list selection. That will make my menu items clickable, and I can use the selection to know what was clicked. Draggable also still works in this case. The problem with this approach is twofold:

  • I'd like to fully control styling, and list selection apply automatic backgrounds to the selected item that I can't figure out how to turn off. Using .listRowBackround does not work since the background behind the menu item is translucent, and setting any color with an opacity less than 100% makes the list controlled background appear
  • I'd also like to know if a user taps on an already selected menu item to trigger some behaviour specific to that action. This isn't possible since I don't control the onTapGesture -- it is handled by the List internally

Does anyone have any ideas on how to approach this?

Thanks!

   

Found out the answer myself. Turns out you can use .simultaneousGesture together with .draggable, as long as both are on separate elements:

            HStack() {
                TheDraggableView()
                    .draggable()
            }
            .gesture(SimultaneousGesture(
                TapGesture()
                    .onEnded { _ in
                        // this works
                    }))

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.