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

SwiftUI numberpad(TextField) fail to update the binding variable

Forums > SwiftUI

Hello guys, I am trying to create a Textfield which allows user to enter information and update the binding variable. Generally, user needs to hit the "return" button after entering the data, so that the compiler will update the data. However, I am now using number pad which have no "return" button. Hence, the compiler fail to update the binding object. What should I do ?

Here is my code:

            class UserSettings: ObservableObject {
                  @Published var cost = 0
                  }

            @EnvironmentObject var usersettings: UserSettings

                  TextField("Please enter here", value: $usersettings.cost, formatter: NumberFormatter())
                    .keyboardType(.numberPad)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .font(.title)
                    .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color("DB"),lineWidth: 1))

The cost keep on showing 0 (where the initial value of cost is = 0) after entering a new value.

Thank you so much

2      

Why do you not add a button that user will tap when updated

struct ContentView: View {
    @State private var amount = ""

    var body: some View {
        HStack {
            TextField("Enter Amount", text: $amount)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .keyboardType(.decimalPad)

            Button("Enter") {
                // do something
            }
            .padding(5)
            .cornerRadius(10)
        }
        .padding()
    }
}

or you can do by using an extension on Binding that was used in HWS+ but that more complicated.

2      

@NigelGee

Can you please link to the Binding extension used in HWS+? I want to know more about it.

Thanks!

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.