import SwiftUI
struct ParentView: View {
@State private var isOn = false
var body: some View {
VStack(spacing: 20) {
Text(isOn ? "Switch is ON" : "Switch is OFF")
.font(.title)
ToggleSwitchView(isOn: $isOn)
}
.padding()
}
}
struct ToggleSwitchView: View {
@Binding var isOn: Bool
var body: some View {
Toggle("Toggle Switch", isOn: $isOn)
.toggleStyle(SwitchToggleStyle(tint: .blue))
.accessibilityLabel("Toggle switch")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ParentView()
}
}We use @State in the parent to hold the Boolean value isOn. The child view ToggleSwitchView declares a @Binding variable to receive a reference to this state. This allows the child to update the parent's state directly.
In the parent, we pass $isOn (the binding) to the child. The child uses this binding in the Toggle control, so when the user flips the switch, the parent's isOn updates immediately. The parent's text label reflects this change in real time.
This pattern is common in SwiftUI to let child views communicate changes back to their parents simply and reactively.