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?
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))
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With