Home > Software engineering >  TextField in SwiftUI is suppose to take a number the user enters and display the total for the 50/30
TextField in SwiftUI is suppose to take a number the user enters and display the total for the 50/30

Time:04-10

struct ContentView: View {
//a variable that will hold what the user enters
@State private var amount = ""

// variable for the 50%, 30%, and 20%
var fiftyPercent = 0.5
var thirtyPercent = 0.3
var twentyPercent = 0.2


var body: some View {
    VStack {
        //User enters in amount to be caluclated
        TextField("Enter Amount", text: $amount)
            .textFieldStyle(.roundedBorder)
            .keyboardType(.numberPad)
        
       //Need a button that calculate the 50%, 30%, and 20%
            Button("Calculate") {
              var save = (Double(amount) ?? 0) * fiftyPercent
            }
        
        }
    }     
}

This was my attempt at trying just to get the first part calculated

 Button("Calculate") {
      var save = (Double(amount) ?? 0) * fiftyPercent

What I am wanting to do is, after the user enters amount, that amount will be calculated by the percentages from each calculated result, But I don't know how to add the 30% and 20% in there and then display the results separately. What I am expecting as the result is:

  • Need: <Result from 50%>
  • Save: <Result from 30%>
  • Spending: <Result from 20%>

CodePudding user response:

try something like this:

struct ContentView: View {
//a variable that will hold what the user enters
@State private var amount = ""

@State private var need = 0.0
@State private var save = 0.0
@State private var spending = 0.0

// variable for the 50%, 30%, and 20%
var fiftyPercent = 0.5
var thirtyPercent = 0.3
var twentyPercent = 0.2

var body: some View {
    VStack {
        //User enters in amount to be caluclated
        TextField("Enter Amount", text: $amount)
            .textFieldStyle(.roundedBorder)
         .keyboardType(.numberPad)
        
        //Need a button that calculate the 50%, 30%, and 20%
        Button("Calculate") {
            need = (Double(amount) ?? 0) * fiftyPercent
            save = (Double(amount) ?? 0) * thirtyPercent
            spending = (Double(amount) ?? 0) * twentyPercent
        }
        // display the results
        HStack (spacing: 30) {
            Text("need \(need)")
            Text("save \(save)")
            Text("spending \(spending)")
        }
    }
}
}

CodePudding user response:

The first thing you need to understand is that when working with components in SwiftUI you do not directly access or assign values to them, there is no Text.value for instance, but instead you use properties in your struct and you assign values to those properties and then the components uses the values of those properties.

In this case it is most appropriate to use @State declared properties for this because @State means that the component will be updated automatically when the property it uses gets updated.

So we need 3 properties that can be displayed in 3 Text fields

@State private var need = ""
@State private var save = ""
@State private var spending = ""

They can then be used in the view like in the below example

VStack {
    Text("Needed: \(need)")
    Text("Saved: \(save)")
    Text("Spending: \(spending)")
}

and now the Text fields will be updated when the values are recalculated.

As for the calculations I think the code is clearer if this is all done in a function

private func calculate() {
    guard let value = Double(amount) else {
        need = 0.0
        save = 0.0
        spending = 0.0
        return
    }

    let needPart = 0.5
    let savePart = 0.3
    let spendingPart = 0.2
    
    need = "\(value * needPart)"
    save = "\(value * savePart)"
    spending = "\(value * spendingPart)"
}

In this function we start by checking if the user has entered a valid amount otherwise we reset the properties and exit. If it is valid we perform the calculations. I have moved the percent values into the function since they are not used elsewhere and made them constant since they can't be changed.

And then the action for the Button would change to

Button("Calculate") {
    calculate()
}

Further improvements could be made to the new function like adding rounding of values and other minor things but I leave that for you to explore.

  • Related