我正在尝试为 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/