如何使用 SwiftUI 显示触控条按钮?

How can I display Touch Bar Buttons using SwiftUI?

我正在尝试为 SwiftUI View 添加 Touch Bar 支持。使用视图上的 .touchBar(content: () -> View) 功能似乎有 SwiftUI API,但文档不存在,我无法让 Touch Bar 显示任何内容。

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .touchBar {
                Button(action: {

                }) {
                    Text("do something")
                }
        }
    }
}

此代码确实编译并且 运行,但 Touch Bar 仍然是空的。如何使用 SwiftUI(不是催化剂)让我的触控栏显示内容?

来自这个How to use a SwiftUI touchbar with a NSWindow - Apple Developer Forums的帮助:

Use the focusable() modifier

当您在 .touchBar(content:) 修饰符之前添加 .focusable() 修饰符时,触摸栏会显示文本。

struct ContentView: View {

    var body: some View {
        Text("Hello, World!")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .focusable()
            .touchBar {
                Button(action: {
                    print("Perform some action")
                }) {
                    Text("do something")
                }
        }
    }
}

如果 "Use keyboard navigation to move focus between controls" 签入 System Preferences -> Keyboard -> Shortcuts,则无法使用 .focusable。为了解决这个问题,我这样做了:

/// Bit of a hack to enable touch bar support.
class FocusNSView: NSView {
    override var acceptsFirstResponder: Bool {
        return true
    }
}

/// Gets the keyboard focus if nothing else is focused.
struct FocusView: NSViewRepresentable {

    func makeNSView(context: NSViewRepresentableContext<FocusView>) -> FocusNSView {
        return FocusNSView()
    }

    func updateNSView(_ nsView: FocusNSView, context: Context) {

        // Delay making the view the first responder to avoid SwiftUI errors.
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            if let window = nsView.window {

                // Only set the focus if nothing else is focused.
                if let _ = window.firstResponder as? NSWindow {
                    window.makeFirstResponder(nsView)
                }
            }
        }
    }
}