Published on: 2024-04-04
State in SwiftUI is pretty simple. If the state property value changes, then the view will be updated as well. We do not update the views directly. This declarative type of programming allows us to …
Here’s a quick example…
Let’s say you have a light switch in your view. This light switch when it’s pressed, will either turn on the light or turn the light off. Let’s say you have a state
property called isOn
that is set to false
, so the light is off
. When we press that light switch, this will trigger the state property value to change from isOn
is false
to true
. As you can tell, we are not explicitly updating the view, but instead, the view is updating based on the state property changes from false
to true
.
The Binding
property is reliant on the fact that you have a State
property already in a view. All this Binding property does, is makes sure that the State
property properly changes when changed from a different view.
Here’s a quick example…
Let’s say there is a parent view, (profile
) and a child view inside profile
, called (contact-card
). So, if we are editing this contact-card
view and that should trigger a change in the profile
view’s State
property, let’s call it (address
). This is a prime example of using the Binding
property wrapper. So, when the user decides to change the address
field in contact-card
(aka child view), this will update the State
property of profile
(aka parent view).
Great! We’ve learned about @State and @Binding and how they relate to one-another. Let’s continue to learn more about SwiftUI fundamentals and concepts together! Stay tuned for the next blog post.