@State Vs Binding
Sakshi! Let's clarify what @Binding
does and why it's different from a normal variable or @State
in SwiftUI.
🔁 What is @Binding
?
@Binding
is a way for a child view to read and write a value that is owned by its parent.
It's like saying:
“I don’t own this value, but I want to access and change it directly from my parent.”
🧠 Difference Between @State
and @Binding
Property Wrapper | Ownership | Can Modify State? | Use Case |
---|---|---|---|
@State | Owned by this view | ✅ Yes | When this view controls the state |
@Binding | Owned by parent | ✅ Yes (through parent) | When this view uses or modifies state passed down from parent |
🧩 In Your Case:
✅ You used:
swiftstruct imageProfile: View {
@Binding var isSelected: Bool
...
}
This means imageProfile
doesn't own isSelected
, but gets it from Home
like this:
swiftimageProfile(isSelected: $isImageChanged)
This lets the imageProfile:
-
Show different images based on the parent’s state.
-
Change that state if needed (e.g., on tap).
🔁 Without @Binding
, like this:
swiftstruct imageProfile: View {
var isSelected: Bool // Not a binding
}
-
It can read the value, but not update it.
-
Useful for display-only views, not interactive ones.
🧪 Example Summary
With @Binding
:
swift@Binding var isSelected: Bool // shared from parent
isSelected.toggle() // updates parent's value
With @State
:
swift@State private var isSelected: Bool = false // independent local state
Let me know if you want a visual example like toggling checkmarks, radio buttons, etc., with multiple bindings!
No comments:
Post a Comment