我正在开发一个 SwiftUI 视图,其中包含两个文本字段,一个用于金额,另一个用于百分比。两个 TextField 都使用 $ 符号绑定到各自的 @State 变量。
struct ContentView2: View {
@State private var amount: String = ""
@State private var percentage: String = ""
var body: some View {
VStack {
TextField("enter value here", text: $amount)
TextField("enter percentage here", text: $percentage)
.onChange(of: amount, perform: onAmountChange(_:))
.onChange(of: percentage, perform: onPercentageChange(_:))
}
.padding()
}
func onAmountChange(_ newValue: String) {
// while setting percentage, `percentage` is a state property that triggers onAmountChange(_:)
percentage = newValue
// Is there a way to stop triggering the onPercentageChange(_:) method here?
}
func onPercentageChange(_ newValue: String) {
// while setting amount, `percentage` is a state property that triggers onPercentageChange(_:)
amount = newValue
// Is there a way to stop triggering the onAmountChange(_:) method here?
}
}
```
Issue:
The problem I'm facing is that when I update the amount, it triggers the onAmountChange(_:) method, which sets the percentage. However, setting the percentage also triggers the onPercentageChange(_:) method, creating a circular dependency
Question:
Is there a way to prevent this circular dependency and avoid the onAmountChange(_:) method from triggering when setting percentage, and vice versa? I want to update the values of amount and percentage without calling second function. Any guidance or alternative approaches would be highly appreciated! Thank you!