2

我正在NSTouchBar使用情节提要为我的应用程序构建一个。

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

像往常一样,没有文档告诉你如何做到这一点。

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

但是,您可以通过使用带有 NSTouchBarItem 的 escapeKeyReplacementItemIdentifier 将“esc”的内容更改为其他内容,例如“done”或任何内容,甚至是图标。

但这太模糊了,无法理解。

有任何想法吗?


这就是我到目前为止所做的。

NSTouchBar在情节提要上添加了一个按钮并将其标识符更改为newESC. 我以编程方式添加了这一行:

self.touchBar.escapeKeyReplacementItemIdentifier = @"newESC";

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

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

就是现在

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

ESC的仍然占据它在酒吧的空间。

4

1 回答 1

2

这是通过创建一个触摸栏项目来完成的,假设 aNSCustomTouchBarItem包含 a 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")
}
于 2017-07-01T16:58:10.537 回答