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      

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.