Skip to content

Instantly share code, notes, and snippets.

@joelekstrom
Last active March 19, 2026 16:17
Show Gist options
  • Select an option

  • Save joelekstrom/91dad79ebdba409556dce663d28e8297 to your computer and use it in GitHub Desktop.

Select an option

Save joelekstrom/91dad79ebdba409556dce663d28e8297 to your computer and use it in GitHub Desktop.
A view modifier that can reliably detect double clicks on macOS, even in List
extension View {
/// Adds a double click handler this view (macOS only)
///
/// Example
/// ```
/// Text("Hello")
/// .onDoubleClick { print("Double click detected") }
/// ```
/// - Parameters:
/// - handler: Block invoked when a double click is detected
func onDoubleClick(handler: @escaping () -> Void) -> some View {
modifier(DoubleClickHandler(handler: handler))
}
}
struct DoubleClickHandler: ViewModifier {
let handler: () -> Void
func body(content: Content) -> some View {
content.overlay {
DoubleClickListeningViewRepresentable(handler: handler)
}
}
}
struct DoubleClickListeningViewRepresentable: NSViewRepresentable {
let handler: () -> Void
func makeNSView(context: Context) -> DoubleClickListeningView {
DoubleClickListeningView(handler: handler)
}
func updateNSView(_ nsView: DoubleClickListeningView, context: Context) {}
}
class DoubleClickListeningView: NSView {
let handler: () -> Void
init(handler: @escaping () -> Void) {
self.handler = handler
super.init(frame: .zero)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
if event.clickCount == 2 {
handler()
}
}
}
@hrzjanati
Copy link
Copy Markdown

usage?
how to use ?

@joelekstrom
Copy link
Copy Markdown
Author

@hrzjanati there’s an example in the comment:

Text("Hello")
    .onDoubleClick { print("Double click detected") }

@ajaysta
Copy link
Copy Markdown

ajaysta commented Aug 2, 2023

Can we enable VO + Space to mimic double click action when VO enabled ?

@hrzjanati
Copy link
Copy Markdown

@hrzjanati there’s an example in the comment:

Text("Hello")
    .onDoubleClick { print("Double click detected") }

Thank's

@hunter-ji
Copy link
Copy Markdown

This works, thanks! I spent days on this.

@joelekstrom
Copy link
Copy Markdown
Author

Glad to help!

@erichfin
Copy link
Copy Markdown

Joel, this was a super-handy piece of code, thank you! May I ask what licensing you're applying to it?

@joelekstrom
Copy link
Copy Markdown
Author

@erichfin None, feel free to copy/modify/whatever. (I hope this comment can be legally binding 😀)

@erichfin
Copy link
Copy Markdown

Ha, I'll take it! Thank you for the prompt response, and, again, for sharing the code Joel!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment