Date
May. 19th, 2024
 
2024年 4月 12日

Post: OS X: Best practical way to validate NSTouchBar items

OS X: Best practical way to validate NSTouchBar items

Published 12:11 Nov 27, 2016.

Created by @ezra. Categorized in #Programming, and tagged as #macOS.

Source format: Markdown

Table of Content

Protocol and extensions:

@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, *) {
            for window in NSApp.windows {
                for responder in sequence(first: window.firstResponder, next: { $0.nextResponder }) {
                    responder.validateTouchBarItems()
                }
            }
        }
    }
}
Pinned Message
HOTODOGO
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF