我自己改进了我的触摸栏验证系统,并做了以下协议和扩展。
@available(macOS 10.12.1, *)
protocol TouchBarItemValidations: class {
func validateTouchBarItem(_ item: NSTouchBarItem) -> Bool
}
@available(macOS 10.12.1, *)
extension NSTouchBarProvider {
func validateTouchBarItems() {
guard NSClassFromString("NSTouchBar") != nil else { return } // run-time check
guard let touchBar = self.touchBar else { return }
// validate currently visible touch bar items
for identifier in touchBar.itemIdentifiers {
guard let item = touchBar.item(forIdentifier: identifier) as? NSCustomTouchBarItem else { continue }
item.validate()
}
}
}
@available(macOS 10.12.1, *)
extension NSCustomTouchBarItem: NSValidatedUserInterfaceItem {
func validate() {
// validate content control
if let control = self.control,
let action = control.action,
let validator = NSApp.target(forAction: action, to: control.target, from: self)
{
if let validator = validator as? TouchBarItemValidations {
control.isEnabled = validator.validateTouchBarItem(self)
} else if let validator = validator as? NSUserInterfaceValidations {
control.isEnabled = (validator as AnyObject).validateUserInterfaceItem(self)
}
}
}
// MARK: Validated User Interface Item Protocol
public var action: Selector? {
return self.control?.action
}
public var tag: Int {
return self.control?.tag ?? 0
}
// MARK: Private Methods
private var control: NSControl? {
return self.view as? NSControl
}
}
@available(macOS 10.12.1, *)
extension AppDelegate {
func applicationDidUpdate(_ notification: Notification) {
// validate touch bar items
if #available(macOS 10.12.1, *) {
if let window = NSApp.mainWindow {
for responder in sequence(first: window.firstResponder, next: { $0.nextResponder }) {
responder.validateTouchBarItems()
}
}
}
}
}
如果您已经有一个AppDelegate,您应该修改applicationDidUpdate(:_)
它,但除此之外,无需添加任何复杂的内容。您现在可以使用validateTouchBarItem(_:)
or normalvalidateUserInterfaceItem(_:)
来验证您自己的触摸栏项目!
我想这至少对我的要求很有效。