2

我正在尝试为SwiftUI View. 似乎有SwiftUI使用 Views 上的功能的 API .touchBar(content: () -> View),但文档不存在,我无法让我的 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")
                }
        }
    }
}

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

4

2 回答 2

7

如果没有签入“使用键盘导航在控件之间移动焦点”,则使用.focusable不起作用System Preferences -> Keyboard -> Shortcuts。为了解决这个问题,我这样做了:

/// 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)
                }
            }
        }
    }
}
于 2020-06-01T23:20:56.620 回答
2

来自如何使用带有 NSWindow 的 SwiftUI 触摸栏的帮助 - Apple 开发者论坛

使用 focusable() 修饰符

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

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")
                }
        }
    }
}

触控栏图片

于 2020-01-26T14:37:25.070 回答