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

标签 macos swiftui macbookpro-touch-bar

我正在尝试为 SwiftUI View 添加 Touch Bar 支持。似乎有 SwiftUI API 为此使用 View 上的 .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")
                }
        }
    }
}

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

最佳答案

如果没有在 系统偏好设置 -> 键盘 -> 快捷方式 中选中“使用键盘导航在控件之间移动焦点”,则无法使用 .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)
                }
            }
        }
    }
}

关于macos - 如何使用 SwiftUI 显示触控条按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59919050/

相关文章:

swift - didSet 没有被 Swift 中的 Array.append() 调用

javascript - 带有自定义图像的触摸栏图标无法在 Electron 中加载

xcode - Xcode 如何使用 Macbook Pro Touchbar?

ios - 从 Core Data Managed Object Context 中删除插入但未保存的对象

swift - 使用 Binding 确定 SwiftUI 中的字符串更改

swift - TableView 对最佳窗口宽度的约束

ios - 防止 SwiftUI 系统镜像动态更改导航栏项目的大小

xcode - 完全重新安装 Xcode 9

swift - 无法快速设置 NSImageView 的图像属性

c - OS X 的低级窗口 API