SwiftUI onMoveCommand操作未执行 [英] SwiftUI onMoveCommand actions aren't executed

查看:92
本文介绍了SwiftUI onMoveCommand操作未执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SwiftUI制作macOS应用程序,我想使用内置键盘上的箭头键偏移SwiftUI视图.
我在网上找不到很多资源,但是 onMoveCommand()似乎是我需要的事件处理程序.试用后,我发现为 onMoveCommand()指定的操作似乎没有执行.这是我为了测试而编写的一些代码:

I'm making a macOS app with SwiftUI, and I would like to offset a SwiftUI view using the arrow keys on the built-in keyboard.
I couldn't find many resources online, but onMoveCommand() appears to be the event handler I need. Upon trying it out, I discovered that the action I specified for onMoveCommand() does not appear to be executed. Here's some code I wrote just to test it out:

struct ContentView: View {
    var body: some View {
        Text("Hello")
            .onAppear() {
                print("Appeared!")
            }
            .onMoveCommand() { (direction) in
                print("Moved!")
            }
            .onTapGesture() {
                print("Tapped!")
            }
    }
}

onMoveCommand()不打印已移动!"当我按箭头键时,会播放错误警报声音,并且什么也没打印. onAppear()成功打印出出现!"视图出现时显示一条消息,并且 onTapGesture()打印已轻按!".每当我单击文本时都正确.这似乎告诉我,这些视图事件的基本语法是正确的,但是我错误地实现了 onMoveCommand().
现在,我只希望我的应用程序在按下箭头键时将某些内容打印到Xcode控制台,并能够区分按下哪个箭头键.有人可以解释我做错了什么吗?

onMoveCommand() does not print "Moved!" when I press the arrow keys, instead I get the error alert sound played, and nothing is printed. onAppear() successfully prints the "Appeared!" message when the view appears, and onTapGesture() prints "Tapped!" correctly whenever I click the text. This seems to tell me that the basic syntax I got for these view events is correct, but I implemented onMoveCommand() incorrectly.
For now I only want my app to print something to the Xcode console when the arrow keys are pressed, and to be able to distinguish which arrow key was pressed. Can someone please explain what I did wrong?

推荐答案

键盘事件仅由焦点视图处理,因此解决方法是

Keyboard events are handled only by view in focus, so fix is

var body: some View {
    Text("Hello")
        .focusable()         // << here !!
        .onAppear() {
            print("Appeared!")
        }
        .onMoveCommand() { (direction) in
            print("Moved!")
        }
        .onTapGesture() {
            print("Tapped!")
        }
}

已通过Xcode 11.4/macOS 10.15.4测试.确保已在系统偏好设置"中打开了键盘导航.

Tested with Xcode 11.4 / macOS 10.15.4. Make sure you have turned on keyboard navigation in System Preferences.

这篇关于SwiftUI onMoveCommand操作未执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆