Duck
Duck

Reputation: 35953

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

Upvotes: 1

Views: 288

Answers (1)

Eric Aya
Eric Aya

Reputation: 70108

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
}

Upvotes: 2

Related Questions