How to Make Double Click work on a NavigationLink (SwiftUI)?
--
It’s actually ridiculous that this story needs to be written. Something as basic as detecting a double mouse click on a NavigationLink
should be as easy as using the .onTapGesture(count: 2) {}
event modifier. However if you arrived at this story there is a great chance you will have noticed that it doesn’t work as you would expect it and you are eager to find a workaround. I am here to tell you that there is and I am going to show you how.
Reproduce the Problem
Xcode 14 (beta 3)
macOS Ventura (13)
Expected Results
I would expect that when I click anywhere in the row the item will be selected. When I double click on the row it would show the message Double Click Detected
in the console.
Actual Results
When I click on the text (1) the item will not get selected. When I double click on the text the message Double Click Detected
is shown in the console. So its partially what I expected.
The opposite happens when you click on the rest of the space of the row. When I click on the space (2) the item will get selected. When I double click nothing will appear in the console.
The Workaround
We need a view with the same size as the navigation link (item row) that detects events and forwards them to the view below it. A passthrough view. This view doesn’t exist in the SwiftUI universe so we need to create one ourselves.
This NSView
accepts a mouseDownHandler
which will fire when a mouse down event is detected. SwiftUI does not work with NSView
so we need to bring it over using a NSViewRepresentable
.