1

我正在尝试在 SwiftUI 中为我的 MacOS 应用程序添加 TouchBar 支持。

我发现我必须打电话..

  NSApp.isAutomaticCustomizeTouchBarMenuItemEnabled = true

.. 在我的 AppDelegate 中。但是现在创建TouchBar. 我可以将它添加到我的 Mac 应用程序菜单的情节提要中,还是需要以编程方式创建它?

当我遵循 Apple 文档时,我明白了这一点:

您可以通过向情节提要中的视图控制器添加一个 Touch Bar 来创建一个 Touch Bar,或者通过重写 NSResponder 的 makeTouchBar() 函数以编程方式创建一个 Touch Bar。

是否可以创建一个自己的 NSViewController,然后将其嵌入到 NSNiewController 中?

也许有人对我如何在 SwiftUI 中支持 TouchBar 有一个很好的建议。

4

1 回答 1

1

最简单的方法是在您的逻辑适用时为视图使用特定标识符,如下例所示

struct ContentView: View {
  var body: some View {
     SomeView()      // << your view here 
        .touchBar {
            Button("Do") {
               // .. Do something here
            }
        }
  }
}

因此,当视图出现时,相关的 Touch Bar 按钮也会出现。

对于更复杂的情况,您可以查看 atTouchBar和相应的扩展名

extension View {

    /// Sets the `TouchBar` to be shown in the Touch Bar when applicable.
    @available(iOS, unavailable)
    @available(tvOS, unavailable)
    @available(watchOS, unavailable)
    public func touchBar<Content>(_ touchBar: TouchBar<Content>) -> some View where Content : View

    /// Sets the `TouchBar` content to be shown in the Touch Bar when applicable.
    @available(iOS, unavailable)
    @available(tvOS, unavailable)
    @available(watchOS, unavailable)
    public func touchBar<Content>(@ViewBuilder content: () -> Content) -> some View where Content : View
}
于 2020-05-08T16:14:19.457 回答