UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Submit TextField when using .keyboardType(.numberPad) ???

Forums > SwiftUI

@SD449  

Is it possible to submit a TextField when using the numberPad? Or configuer a keyboard toolbar button to submit?

TextField("Enter your answer here", text: $answer)
    .keyboardType(.numberPad)
    .focused($isFocused)

I have added a button to keyboard toolbar which removes focus but doesn't submit.

.toolbar {
    ToolbarItemGroup(placement: .keyboard) {
        Spacer()

        Button("Done") {
            isFocused = false
        }
     }
}

I tried adding return after removing the focus but it was no different.

I have an onSubmit() action which works when pressing enter on a physical keyboard, but not using the "Done" button.

.onSubmit() {
     showingAlert = checkAnswer(answer: Int(answer) ?? 0)
}

If I comment out the .keyboardType and use the standard keyboard which has the return button, the code works as expected and I can even change this button using .submitLabel(.done) but obviously this doen't apply to the .numberPad keyboard type.

I know I can run a function on the button press using action: but this is not the way I wanted to go.

I hope the above makes sence and thank you for reading

1      

Not sure but do you want showingAlert = checkAnswer(answer: Int(answer) ?? 0) to happen when user taps the Done button? If so then put that in the Button as well.

.toolbar {
    ToolbarItemGroup(placement: .keyboard) {
        Spacer()

        Button("Done") {
            showingAlert = checkAnswer(answer: Int(answer) ?? 0)
            isFocused = false
        }
     }
}

2      

@SD449  

Yes that would work.

But how can I have the done buttom work the same (i.e. submit/return) as the normal keyboard or a hardware keyboard?

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.