Overview
- When calling onChange(of:initial:_:) with initial as true, closure called even when the value assigned is the same as previous value (not just the first time, subsequently too).
- However when initial value is false it is called only when value changes.
Questions
- Is this a bug?
- Am I missing something?
Hi,
Is your field optional? If it's optional, the value will be set to nil when it's removed. Otherwise, the field will never be empty and will always retain its value, thus not triggering any change unless that value is different. I have created a small sample view.
struct OnChangeView: View {
@State private var value: Int? = 1
@State private var value2: Int = 2
var body: some View {
VStack {
TextField("val 1", value: $value, format: .number)
TextField("val 2", value: $value2, format: .number)
}
.onChange(of: value, initial: true) {
print("value 1", value)
}
.onChange(of: value2, initial: false) {
print("value 2", value2)
}
.onAppear {
value = 1
value2 = 2
}
}
}
#Preview {
OnChangeView()
}
Do you have an example that's different?
Christian