onChange on textField1 to calculate and populate textField2

Hi all,

I am new to SwiftUI. Need help.

I have 2 text fields, based on the amount entered on field1, percentage calculation shold happen and populated in textField2.

        .onChange(of: pnlText) { newValue in
           let formatted = formatInput(newValue)             
           pnlText = formatted          
               if let pnlValue = Double(formatted) {             
                  pnl = pnlValue
                  if open_bal != 0 {                           
                        pnl_pcntText = pnlValue / open_bal
                   } else {
                         pnl_pcntText = 0.0
                             }
                } else {
                       pnl = 0.0
                       pnl_pcntText = 0.0
                    }
           }

I am getting below error.

"The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions".

What is other way to do this. Please help.

Thank you.

It's worth moving the calculation logic into its own function. At the very least it separates the view layout from the logic. It also simplifies the job for the compiler which can lead to the error you got. (Not uncommon in SwiftUI.)

e.g.


struct ContentView: View {
    @State private var value1 = 0.0
    @State private var value2 = 0.0
    let percentage = 0.25 //    25%

    var body: some View {
        VStack {
            TextField("TF1", value: $value1, format: .number)
                .onChange(of: value1) { calculatePercentage() }
            TextField("TF2 (\(percentage)%)", value: $value2, format: .number)
        }
        .padding()
    }

    func calculatePercentage() {
        value2 = value1 * percentage
    }
}

Thank you for quick response.
Tried this, 2nd field is not populated unless if we hit a button.

Is it not recommended in swiftUI?

That's odd. That view works for me, on both macOS and iOS...

Thanks a lot Diggory.

It worked .. (It was other code issue).

1 Like