在AppKit上,菜单项和工具栏项分别有validateMenuItem(_:)
和validateToolbarItem(_:)
。但是,通过新的触摸条项目,没有这种方便的方法来在适当的时候验证适当的项目。验证NSTouchBar项目的最佳实用方法
我每次在更改相关值并调用didSet
(请参阅下面的示例代码)中的验证方法时,都会验证触摸栏项目。但我觉得这不是一个好方法,因为相关的值必须知道有一个触摸栏项取决于它。
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
}
}
我正在使用的另一种方式是可可绑定和KVO,但它并不总是很好。
所以,我很好奇是否有任何推荐或事实标准的方式来验证触摸栏项目,尤其是包含NSButton和NSSegmentedControl。我不想改变物品的可用性,有时候也会根据情况改变它们的图像或颜色。你们如何验证触摸条项目?
这个答案后,我的应用程序已经改进了很多。有关最新的代码,请参阅https://github.com/coteditor/CotEditor/blob/develop/CotEditor/Sources/NSTouchBar%2BValidation.swift。 – 1024jp