何在MacOS上将onCommand与NSMenuItem一起使

何在MacOS上将onCommand与NSMenuItem一起使

本文介绍了SwiftUI-如何在MacOS上将onCommand与NSMenuItem一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到将NSMenuItem与macOS上的SwiftUI onCommand连接的最佳解决方案.

I am trying to find the best solution to connect a NSMenuItem with SwiftUI onCommand on macOS.

当前我正在执行以下操作:

Currently I an doing the following:

  1. 在AppDelegate中,我创建了一个虚拟函数,以便能够列出该函数第一响应者"接收到的动作列表.
@IBAction func changeColor(_ sender: Any) {
    print("Dummy Function")
}
  1. 在Main.storyboard中创建并连接具有First Responder功能的NSMenuItem.

  1. Create and connect a NSMenuItem with the First Responder function in the Main.storyboard.

将所需的代码添加到我的SwiftUI视图

Add the required code to my SwiftUI view

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是第一响应者,我将看到已打印更改颜色操作".如果TextField之前不是First Responder,则View不会成为First Responder.也许这目前是Catalina Beta(19A558d)中的错误,因为我也不太专注于工作.

If the TextField was First Responder before I will see that "Change Color Action" is printed.The View will not become First Responder if the TextField was not First Responder before. Maybe this is currently a bug in Catalina Beta (19A558d) since I don't get focusable to work as well.

推荐答案

我已经能够通过首先创建视图focusable来使它起作用:

I've been able to get this to work by first making the view 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")
        }
    }
}

然后,您还必须选中键盘系统偏好设置"中的使用键盘导航在控件之间移动焦点"复选框

then you also have to check the "Use keyboard navigation to move focus between controls" checkbox in Keyboard System Preferences

这篇关于SwiftUI-如何在MacOS上将onCommand与NSMenuItem一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 09:47