[英]How can I display Touch Bar Buttons using SwiftUI?
I'm trying to add Touch Bar support for a SwiftUI
View
.我正在尝试为SwiftUI
View
添加 Touch Bar 支持。 There seems to be SwiftUI
API for this using the .touchBar(content: () -> View)
function on Views, but documentation is non existent and I can't get my Touch Bar to display anything.在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")
}
}
}
}
This code does compile and run, but the Touch Bar remains empty.这段代码可以编译并运行,但 Touch Bar 仍然是空的。 How can I get my touch bar to display content using SwiftUI (not catalyst)?如何让我的触摸栏使用 SwiftUI(不是催化剂)显示内容?
Using .focusable
doesn't work without "Use keyboard navigation to move focus between controls" checked in System Preferences -> Keyboard -> Shortcuts
.如果没有在System Preferences -> Keyboard -> Shortcuts
选中“使用键盘导航在控件之间移动焦点”,则使用.focusable
不起作用。 To work around that, I did this:为了解决这个问题,我这样做了:
/// 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)
}
}
}
}
}
Help from this How to use a SwiftUI touchbar with a NSWindow - Apple Developer Forums :来自如何使用带有 NSWindow 的 SwiftUI 触摸栏的帮助- Apple 开发者论坛:
Use the focusable() modifier使用 focusable() 修饰符
The touch bar shows the text when you add the .focusable()
modifier just before the .touchBar(content:)
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")
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.