macosnstouchbar

How to detect a Pan Gesture inside a NSTouchBarView


Is it possible to detect a finger pan on a NSTouchBarView?

Sorry for the lack of code but I don't even know where to start.

MacOS is not made for finger touches but the TouchBar is but I do not see how to do it on a NSTouchBarView


Solution

  • I don't know specifically about using NSTouchBarView, but using a pan recognizer in a touch bar usually works like this: create a view, then create a NSPanGestureRecognizer (don't forget to set the target and action) then add the recognizer to the previously created view. Finally, create your NSCustomTouchBarItem and assign the previously created view to the item's view. Quick example in Swift:

    func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItemIdentifier) -> NSTouchBarItem? {
    
        switch identifier {
        case NSTouchBarItemIdentifier.yourCustomItem:
            return itemWithRecognizer(identifier: identifier)
        default:
            return nil
        }
    
    }
    
    func itemWithRecognizer(identifier: NSTouchBarItemIdentifier) -> NSTouchBarItem {
        let customView = NSView()
        customView.wantsLayer = true
        let recognizer = NSPanGestureRecognizer()
        recognizer.target = self
        recognizer.action = #selector(doSomething)
        customView.addGestureRecognizer(recognizer)
        let item = NSCustomTouchBarItem(identifier: identifier)
        item.view = customView
        return item
    }
    
    func doSomething() {
        // gesture was activated
    }