In SwiftUI, @State and @Binding are property wrappers that manage data flow and state changes in views.
@State
Characteristics:
- Owned by the view.
- The initial value is set by the view.
- Changes trigger view updates.
Use cases:
- Local state management.
- Simple forms.
- Toggle buttons.
Example:
struct CountNumberView: View {
@State private var number = 0
var body: some View {
Button("Increment") {
number += 1
}
Text("number: \(number)")
}
}
@Binding
Characteristics:
- References an external state.
- Changes update the external state.
- External changes update the view.
- Parent-child view communication.
- Shared state between views.
- Complex forms.
Example:
struct ChildView: View {
@Binding var name: String
var body: some View {
TextField("Enter name", text: $name)
}
}
struct ParentView: View {
@State private var name = ""
var body: some View {
ChildView(name: $name)
Text("Name: \(name)")
}
}
Key differences
2. Direction: @State is one-way (view-only), while @Binding is two-way (view-external).
3. Updates: @State updates trigger view updates while @Binding updates trigger external state changes.
No comments:
Post a Comment