On AppKit, menu items and toolbar items have validateMenuItem(_:)
and validateToolbarItem(_:)
respectively. However, by new touch bar items, there is no such convenience method to validate appropriate items at the right moment.
I'm now validating touch bar items every time when I change the related values and invoke a validation method in didSet
(see the following sample code). But I feel it is not a good way because the related values must know there is a touch bar item depending on it.
var foo: Foo? {
didSet {
if #available(macOS 10.12.1, *), NSClassFromString("NSTouchBar") != nil {
self.validateTouchBarItem(identifier: .foo)
}
}
}
@available(macOS 10.12.1, *)
func validateTouchBarItem(identifier: NSTouchBarItemIdentifier) {
guard
let item = self.touchBar?.item(forIdentifier: identifier),
let button = item.view as? NSButton
else { return }
switch identifier {
case NSTouchBarItemIdentifier.foo:
button.isEnabled = (self.foo != nil)
default: break
}
}
Another way I'm using is the Cocoa-binding and KVO, however, it doesn't always work well.
So, I'm curious whether there is any recommended or a defacto-standard way to validate touch bar items, especially containing NSButton and NSSegmentedControl. I wanna change not only the availability of items but sometimes also images or colors of them depending on the situation. How do you guys validate touch bar items?