Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change value of Text while typing in TextField at a time without clicking anywhere - SwiftUI

I'm trying to change value of Text while typing in TextField. When i type anything in TextField, i want to do some calculation with Textfield value and display it on Text. In Swift, we have func textFieldDidChange(_ textField: UITextField) delegate method of UITextField to track that UITextField is changed.

In SwiftUI, i tried to create TextField with onEditingChanged. but somehow it is not going into that block. I don't know if i am doing anything wrong with it or not.

    @State var totalAmount: String = ""
    @State var addAmount: String = ""
    var body: some View {

            HStack {
                TextField("0.0", text: $totalAmount, onEditingChanged: { _ in
                    self.addAmount = //doing some calculation with totalAmount
                })
                Text(self.addAmount)

            }
    }

Can anyone help with this?

like image 383
Anjali Kevadiya Avatar asked Dec 23 '22 21:12

Anjali Kevadiya


1 Answers

SwiftUI is not like Cocoa. It is not event-driven, and there is no communication from one interface object to another. There is only data. Data flows thru state variables. It flows up by a state variable's binding and down by a state variable's value.

So you don't need an onEditingChanged event, or any other event. $totalAmount is a binding. It changes when the text field's text changes, automatically.

Moreover, totalAmount is a state variable. If the Text uses this as its value, directly or indirectly, the text changes automatically when totalAmount changes.

So just use a calculated variable that depends on totalAmount and make that the value of the Text and you're done.

Extremely basic example:

struct ContentView : View {
    @State var totalAmount = ""
    let addAmount = 10.0 // or whatever
    var calc : Double { (Double(totalAmount) ?? 0.0) + addAmount } // or whatever
    var body: some View {
        HStack {
            TextField("Type a number", text: $totalAmount)
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .frame(width:100)
            Text(String(self.calc))
        }
    }
}
like image 128
matt Avatar answered Jan 19 '23 01:01

matt