iOS Swift - State Management in SwiftUI
You want a child view to toggle a Boolean value in the parent and also perform a side effect when toggled. Which approach correctly uses @Binding and triggers the side effect in the parent?
struct ParentView: View {
@State private var isOn = false
var body: some View {
ChildView(isOn: $isOn)
.onChange(of: isOn) { newValue in
print("Toggled to \(newValue)")
}
}
}
struct ChildView: View {
@Binding var isOn: Bool
var body: some View {
Toggle("Switch", isOn: $isOn)
}
}