繁体   English   中英

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

[英]How can I display Touch Bar Buttons using SwiftUI?

我正在尝试为SwiftUI View添加 Touch Bar 支持。 SwiftUI使用.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(不是催化剂)显示内容?

如果没有在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)
                }
            }
        }
    }
}

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

使用 focusable() 修饰符

当您在.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")
                }
        }
    }
}

触控栏图片

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM