Detecting Keypress on Software Keyboard

It seems that onKeyPress only works with a hardware keyboard. Is there any way to detect a keypress on a software keyboard?

@PeteTheGolfer

A software keyboard only appears when there is a TextField available to enter data into.

I get the software keyboard. I tried to use .onKeyPress() to detect when a key is pressed. It works on a hardware keyboard, but not a software keyboard. I was asking if there is a way to detect a key press on a software keyboard.

Yeah I understood that you wanted to detect a software key but the point I was making is that for the software keyboard to be visible you need a TextField that you tap on for that keyboard to appear. As far a detecting any character is concerned you could use an .onChange modifier which monitors the bound variable used in the TextField. When a key is tapped, do something with it.

I tried using onChange on the bound variable. The problem is, when I detect a keypress, I have to do something that changes the value in the variable. This kicks of the onChange again, ad infinitum.

What I’m trying to do is enter a dollar amount into a variable, so I don’t have to press the decimal key. the first character goes into the cents position. Th next character causes the current value to be multiplied by 10, then the new character goes into the cents position. In other words, if ‘total’ is the variable (a Double), then

total = total * 10 + Double(key)! / 100

Why not change the keyboard type for that particular field so that the user is presented with a decimal keypad? It means that you are using standard iOS methodology that every user is familiar with. At the same time you can right justify the content as in this example:

struct RightJustifiedView: View {
    @State private var textFieldBinding = ""

    var body: some View {
        HStack(spacing: 20){
            Text("Value:")
            Spacer()
            VStack(alignment: .trailing){
                TextField("", text: $textFieldBinding)
                    .padding(.horizontal, 20)
                    .keyboardType(.decimalPad)
                    .textFieldStyle(.roundedBorder)
                    .multilineTextAlignment(.trailing)
            }
        }
        .padding(.leading, 10)
        .padding(.horizontal)
    }
}

Using .decimalPad means you have to type the decimal point to enter cents. I would rather use .numberPad and have the cents implied, so if I enter the characters 1 2 3, then the display will show:

after pressing 1 - 0.01
after pressing 2 - 0.12
after pressing 3 - 1.23

There is an app called ‘Accounts3’ that does this, but I expect that it was written using UIKit instead of SwiftUI. I suppose UIKit has more keyboard control.

No idea.

Good luck with your challenge.