Forked from joelekstrom/SwiftUIDoubleClickModifier.swift
Created
March 11, 2024 12:02
-
-
Save SergLam/f113ae54782f8e3cad99c63fea8e606e to your computer and use it in GitHub Desktop.
A view modifier that can reliably detect double clicks on macOS, even in List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment