Sure! Here's a SwiftUI macOS app that allows you to test your keyboard without hardcoding keys. This app will display the key event when you press any key on your keyboard:
-
Create a new macOS App project using SwiftUI in Xcode.
-
Replace the content of ContentView.swift with the following code:
import SwiftUI
struct ContentView: View {
@State private var keyPressed = ""
var body: some View {
VStack {
Text("Press any key:")
.font(.largeTitle)
Text(keyPressed)
.font(.system(size: 50))
.padding()
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.focusable()
.background(
KeyEventHandlingView(keyPressed: $keyPressed)
)
}
}
struct KeyEventHandlingView: NSViewRepresentable {
@Binding var keyPressed: String
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeNSView(context: Context) -> NSView {
let view = NSView()
view.delegate = context.coordinator
return view
}
func updateNSView(_ nsView: NSView, context: Context) {}
class Coordinator: NSObject, NSViewDelegate {
var parent: KeyEventHandlingView
init(_ parent: KeyEventHandlingView) {
self.parent = parent
}
override func keyDown(with event: NSEvent) {
if let characters = event.characters {
parent.keyPressed = characters
}
}
override func keyUp(with event: NSEvent) {
parent.keyPressed = ""
}
}
}
- Run the app on your MacBook.
Now you have a simple keyboard tester that displays the key you press without hardcoding all the keys. It will work with different keyboard layouts as well. Note that this app will only run on macOS, not on iOS.