英文:
How to detect specific keys on keyboard keypress?
问题
Sure, here's the translated code portion:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Rectangle()
.fill(.white)
.frame(width: 100, height: 100)
.onHover { hover in
func doSomething(event: NSEvent) -> NSEvent? {
guard !event.isARepeat else {
return nil
}
print("按下字母 'A' 的键码是" + event.keyCode.description)
if event.keyCode == 0 {
print("按下了字母 'A'")
return nil
}
return event
}
}
}
.padding()
}
}
Please note that I've translated the code while preserving its structure.
英文:
How to detect letter 'A' keypress in swiftUI? macOS.
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Rectangle()
.fill(.white)
.frame(width: 100, height: 100)
.onHover { Bool in
func doSomething(event: NSEvent) -> NSEvent? {
guard !event.isARepeat else {
return nil
}
print ("key code for letter 'A' is" + event.keyCode.description)
if event.keyCode == 10 {
print("Letter 'A' pressed")
return nil
}
return event
}
}
}
.padding()
}
}
P.S: To the person who will give negative votes for this question anyways --> it's a tradition in stackoverflow to give negative votes as much as possible. so, go ahead.
答案1
得分: 0
struct ContentView: View {
@State private var keyPressed: String = ""
var body: some View {
Text(keyPressed)
.onAppear {
NSEvent.addLocalMonitorForEvents(matching: [.keyDown]) { nsevent in
if let char = nsevent.characters {
keyPressed = char
}
return nsevent
}
}
}
}
英文:
The following code lets you type any key and display its character.
Adapt this to detect specific key pressed on the keyboard in macos.
struct ContentView: View {
@State private var keyPressed: String = ""
var body: some View {
Text(keyPressed)
.onAppear {
NSEvent.addLocalMonitorForEvents(matching: [.keyDown]) { nsevent in
if let char = nsevent.characters {
keyPressed = char
}
return nsevent
}
}
}
}
Do not declare functions, such as func doSomething(event: NSEvent)
inside the .onHover{...}
, it is not the appropriate place to do this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论