替换 NSTouchBar 上的 ESC 按钮

Replacing the ESC button on a NSTouchBar

我正在使用 Storyboard 为我的应用构建 NSTouchBar

我想用其他东西替换 ESC 按钮。

像往常一样,没有文档告诉您如何操作。

我在网上搜索过,发现一些模糊的信息,比如

You can change the content of "esc" to something else, though, like "done" or anything, even an icon, by using escapeKeyReplacementItemIdentifier with the NSTouchBarItem.

但是这个太模糊了,不好理解。

有什么想法吗?


这是我目前所做的。

我在故事板上向 NSTouchBar 添加了一个按钮,并将其标识符更改为 newESC。我以编程方式添加了这一行:

self.touchBar.escapeKeyReplacementItemIdentifier = @"newESC";

当我 运行 应用程序时,ESC 键现在是不可见的,但仍然占据它在栏上的 space。应该替换它的按钮出现在它旁边。所以那个酒吧是

`ESC`, `NEW_ESC`, `BUTTON1`, `BUTTON2`, ...

现在

`ESC` (invisible), `NEW_ESC`, `BUTTON1`, `BUTTON2`, ...

旧的ESC仍然占据它的space吧。

这是通过创建一个触摸条项目来完成的,假设一个 NSCustomTouchBarItem 包含一个 NSButton,并将这个项目与其自己的标识符相关联。

然后使用 另一个 标识符执行您通常的逻辑,但您将之前创建的标识符添加为 ESC 替换。

Swift中的快速示例:

func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItemIdentifier) -> NSTouchBarItem? {

    switch identifier {
    case NSTouchBarItemIdentifier.identifierForESCItem:
        let item = NSCustomTouchBarItem(identifier: identifier)
        let button = NSButton(title: "Button!", target: self, action: #selector(escTapped))
        item.view = button
        return item
    case NSTouchBarItemIdentifier.yourUsualIdentifier:
        let item = NSCustomTouchBarItem(identifier: identifier)
        item.view = NSTextField(labelWithString: "Example")
        touchBar.escapeKeyReplacementItemIdentifier = .identifierForESCItem
        return item
    default:
        return nil
    }

}

func escTapped() {
    // do additional logic when user taps ESC (optional)
}

我还建议为标识符做一个扩展(类别),它可以避免用字符串文字拼写错误:

@available(OSX 10.12.2, *)
extension NSTouchBarItemIdentifier {
    static let identifierForESCItem = NSTouchBarItemIdentifier("com.yourdomain.yourapp.touchBar.identifierForESCItem")
    static let yourUsualIdentifier = NSTouchBarItemIdentifier("com.yourdomain.yourapp.touchBar.yourUsualIdentifier")
}