NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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

   

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.

   

Hacking with Swift is sponsored by Stream

SPONSORED Check out Stream's cross-platform open source chat SDK on GitHub! Write once and deploy your app with fully featured chat UI on iOS and macOS.

Go to GitHub

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

Reply to this topic…

You need to create an account or log in to reply.

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.