Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show touch bar in a viewcontroller

I want to develop an app with touch bar. I searched on internet and saw some tutorials. They all make a demo with windowcontroller and just override makeTouchBar() or drag touchbar in storyboard then there is a touchbar. But I want to make touchbar be different in viewcontroller. Then I draged a touchbar into a viewcontroller in storyboard and bind the touchbar in viewcontroller.

enter image description here

bind(#keyPath(touchBar), to: self, withKeyPath: #keyPath(touchBar), options: nil)

But when I run the project I can't find my touchbar and then I print touchbar.isVisible and I found that the value is false.

image description here

So how to show a touchbar in a viewcontroller. Thanks!

like image 837
bewils Avatar asked Feb 20 '17 10:02

bewils


2 Answers

You can try this in the ViewController, it works for me:

override func viewDidAppear() {
        super.viewDidAppear()
        self.view.window?.unbind(#keyPath(touchBar)) // unbind first
        self.view.window?.bind(#keyPath(touchBar), to: self, withKeyPath: #keyPath(touchBar), options: nil)
}
like image 156
Loys Avatar answered Oct 20 '22 13:10

Loys


Actually Loys' answer is right.

NSTouchBar discovery by the system proceeds as shown from bottom-to-top in this list:

  1. App delegate
  2. App object
  3. Main window’s controller
  4. Main window’s delegate
  5. Main window
  6. Main window’s first responder
  7. Key window’s controller
  8. Key window’s delegate
  9. Key window
  10. Key window’s first responder

Which means it will try to find in the windowcontroller or app delegate.

But you can overrite it, put these code in the viwController to unbind window's touchBar and bind it to the view.

 deinit {
        self.view.window?.unbind(#keyPath(touchBar))
    }

    override func viewDidAppear() {
        super.viewDidAppear()
        if #available(OSX 10.12.1, *) {
           self.view.window?.unbind(#keyPath(touchBar)) // unbind first
           self.view.window?.bind(#keyPath(touchBar), to: self, withKeyPath: #keyPath(touchBar), options: nil)
        }
    }

Refer from:

NSTouchBar Documentation

WWDC Sample Code -> In this example, it bind nstouchbar to view controller.

like image 2
XueYu Avatar answered Oct 20 '22 15:10

XueYu