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.
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.
So how to show a touchbar in a viewcontroller. Thanks!
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)
}
Actually Loys' answer is right.
NSTouchBar discovery by the system proceeds as shown from bottom-to-top in this list:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With