Listen for Touch Events on MacOS (Trackpad)

21 views Asked by At

Trying to listen for touch events on the Mac trackpad; here's what I have so far, but, nothing seems to be registering as a touch event:

import SwiftUI
import Cocoa

// TrackpadTouchView for handling touch events
class TrackpadTouchView: NSView {
    
    override func viewDidMoveToWindow() {
        super.viewDidMoveToWindow()
        window?.makeFirstResponder(self)
    }

    override func touchesBegan(with event: NSEvent) {
        super.touchesBegan(with: event)
        let touches = event.touches(matching: .any, in: self)
        processTouches(touches, phase: "began")
    }

    override func touchesMoved(with event: NSEvent) {
        super.touchesMoved(with: event)
        let touches = event.touches(matching: .any, in: self)
        processTouches(touches, phase: "moved")
    }

    override func touchesEnded(with event: NSEvent) {
        super.touchesEnded(with: event)
        let touches = event.touches(matching: .any, in: self)
        processTouches(touches, phase: "ended")
    }

    override func touchesCancelled(with event: NSEvent) {
        super.touchesCancelled(with: event)
        let touches = event.touches(matching: .any, in: self)
        processTouches(touches, phase: "cancelled")
    }

    private func processTouches(_ touches: Set<NSTouch>, phase: String) {
        for touch in touches {
            let location = touch.location(in: self)
            print("Touch \(phase) at \(location)")
        }
    }
    
    override var acceptsFirstResponder: Bool {
        return true
    }
}

// SwiftUI wrapper for TrackpadTouchView
struct TrackpadTouchRepresentable: NSViewRepresentable {
    
    func makeNSView(context: Context) -> TrackpadTouchView {
        TrackpadTouchView()
    }
    
    func updateNSView(_ nsView: TrackpadTouchView, context: Context) {
        // Update the view if needed
    }
}

struct ContentView: View {
    var body: some View {
        TrackpadTouchRepresentable()
            .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

I tried updating like so

  override func viewDidMoveToWindow() {
        super.viewDidMoveToWindow()
        print("View did move to a window.")
        if let window = window, window.makeFirstResponder(self) {
            print("TrackpadTouchView is now the first responder.")
        } else {
            print("Failed to become first responder.")
        }
    }

    override func resignFirstResponder() -> Bool {
        print("TrackpadTouchView is resigning first responder.")
        // Return false to prevent the view from resigning its first responder status
        return false
    }

But got these logs:

View did move to a window.
TrackpadTouchView is now the first responder.
0

There are 0 answers