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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.