我正在尝试找到在 macOS 上将 NSMenuItem 与 SwiftUI onCommand 连接的最佳解决方案。
目前我正在做以下事情:
- 在 AppDelegate 中,我创建了一个虚拟函数,以便能够列出第一响应者收到的操作列表的函数。
@IBAction func changeColor(_ sender: Any) {
print("Dummy Function")
}
创建 NSMenuItem 并将其与 Main.storyboard 中的 First Responder 函数连接。
将所需的代码添加到我的 SwiftUI 视图中
struct TestView: View {
let changeColor = #selector(AppDelegate.changeColor(_:))
var body: some View {
VStack {
TextField("Text", text: .constant(""))
Text("Hello World!")
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onCommand(changeColor) {
print("Change Color Action")
}
}
}
如果文本字段之前是第一响应者,我将看到打印“更改颜色操作”。
如果 TextField 之前不是第一响应者,则视图将不会成为第一响应者。也许这目前是 Catalina Beta (19A558d) 中的一个错误,因为我也无法集中精力工作。
我已经能够通过首先创建视图来使其工作focusable
:
struct TestView: View {
let changeColor = #selector(AppDelegate.changeColor(_:))
var body: some View {
VStack {
TextField("Text", text: .constant(""))
Text("Hello World!")
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.focusable() // Add this
.onCommand(changeColor) {
print("Change Color Action")
}
}
}
那么您还必须选中“键盘系统偏好设置”中的“使用键盘导航在控件之间移动焦点”复选框
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)