【问题标题】:Replacing the ESC button on a NSTouchBar替换 NSTouchBar 上的 ESC 按钮
【发布时间】:2017-07-01 14:45:42
【问题描述】:

我正在使用情节提要为我的应用构建NSTouchBar

我想用别的东西替换ESC 按钮。

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

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

不过,您可以将“esc”的内容更改为其他内容,例如 “完成”或任何东西,甚至是一个图标,通过使用 带有 NSTouchBarItem 的 escapeKeyReplacementItemIdentifier。

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

有什么想法吗?


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

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

self.touchBar.escapeKeyReplacementItemIdentifier = @"newESC";

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

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

现在

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

旧的ESC 仍在吧台上占据它的空间。

【问题讨论】:

  • 标题 NSTouchBar.h 在文档方面做了一些尝试。 cmets 不是正确的 headerdocs,所以我猜他们没有进入已发布的文档集。
  • 苹果应该避免写文档,它们都是垃圾。我已经阅读了,但仍然不知道该怎么做。
  • “应该避免”我的意思是,他们基本上已经这样做了! :P
  • 我的意思是完全。现在很明显,他们将开发人员视为三等公民。他们更鄙视我们和 MacOS 开发者。

标签: macos cocoa nstouchbar


【解决方案1】:

这是通过创建一个触摸栏项目来完成的,比如一个包含NSButtonNSCustomTouchBarItem,并将该项目与其自己的标识符相关联。

然后使用 another 标识符执行通常的逻辑,但添加之前创建的标识符作为 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")
}

【讨论】:

  • 哈哈...事情变得更糟了...我创建了this other question 来处理NSTouchBar 委托方法没有触发的事实...如果我解决了另一个问题,你的问题可能会起作用,它会解决这个问题......这是一个组合......?
  • 顺便说一句,yourUsualIdentifier 是什么,你不应该从第一个 case 块(代表 esc 的块)内部调用 touchBar.escapeKeyReplacementItemIdentifier 吗?
  • yourUsualIdentifier 只是项目的另一个标识符的示例,这里是一个文本字段。由于 ESC 替换是 touchbar 上的一个属性,因此从哪里调用它并不重要。
  • objective.c 版本?谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
  • 2021-12-18
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多