TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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 Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.