Did you try to use .onChange ? If you want to detect a pressed key (but not a typed character in the TextField, that will not do it.
or onKeyPress ?
More details here: https://www.avanderlee.com/swiftui/key-press-events-detection/#:~:text=Key%20press%20events%20detection%20in%20SwiftUI%20allows%20you%20to%20listen,able%20to%20get%20any%20callbacks.
Something like:
struct ContentView: View {
@State private var vText: String = ""
var body: some View {
HStack {
TextField("Enter text", text: Binding(
get: { vText },
set: { newValue in
// print("Text will change to: \(newValue)")
vText = newValue
}
))
.onChange(of: vText) { oldText, newText in
let typed = newText.replacingOccurrences(of: oldText, with: "")
if newText.count < oldText.count {
print("backspace")
} else {
print("typed char is: ", typed)
}
}
}
.onKeyPress(characters: .alphanumerics, /*phases: .up, */action: { keyPress in
print("Released key \(keyPress.characters)")
return .ignored // handled would intercept the typing
})
}
}