Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting from text field string to double

I am currently working on a weight tracking app as a tutorial project for Swift. I am implementing the MVVM pattern, and I have a weightEntry class, where one of the attributes is weight, a Double.

In my view I have one ViewModel object, which has a weightEntry object. I would like to assign the entry in the Weight text field to my weightEntry.weight, however I’m not sure how I could convert the format from string to double in the view?

Below is the code in the view:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    @ObservedObject var mainViewVM = MainViewViewModel()
    
    
    var body: some View {
        VStack(alignment: .leading, spacing: /*@START_MENU_TOKEN@*/nil/*@END_MENU_TOKEN@*/, content: {
            
            
            Text("Weight Tracking App").font(.title)
            
            HStack {
                Text("Add your current weight").font(.subheadline)
                TextField("Weight", text: $mainViewVM.weightEntry.weight)
                    .padding()
                    .keyboardType(.decimalPad)
            }

>Solution :

There is a initializer which can take a Double and a format description , init(_:value:format:prompt:).

TextField("Weight", value: $mainViewVM.weightEntry.weight, format: .number.precision(.fractionLength(1)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading