Why Changing the Injected Property Doesn’t Update My View in SwiftUI? | by Pedro Alvarez | Aug, 2022

Understanding the use cases of Binding and State

Photo by Kelly Sikkema on Unsplash

When I just started with SwiftUI and trained some custom views by myself, I was really confused through this point. Imagine you have like a custom button which I may call SelectionView for convenience purposes which has a boolean indicating if this is or is not selected:

Not selected view
Selected View

It has an initialized property called isSelected which is a boolean and if it’s true, we set its background as a colorful pink, but if it’s false we set the background as the first image with a kinda transparent color. The code for that would be as follows:

We created two binding properties since we desire to update some ViewModel state in the upper level. Now, try to tap the button on the preview and check what happens…Nothing happens at all, right? That’s because the two properties are not State ones.

In SwiftUI, the State wrapper under the hood tells its hierarchy to be rendered again with the new parameters it got. As it’s not a State property, there’s no reason to update the SelectionView ‘s body.

We need to re-instantiate our SelectionView in order to have our new layout. For that, we rely on a State variable in an upper view that shall be responsible of updating all the lower hierarchy. Let’s say we have a ScreenView :

When isSelected is changed, the State variable whose binding was injected changes, so it forces a redraw.

Every time you inject a property into some custom SwiftUI View that is changed inside, in order to reflect your change on the layout, this property shall be a Binding to a State variable in an upper View, otherwise, nothing will redraw. I hope you understood a little bit more about SwiftUI, Binding and State use cases and enjoyed 😉

News Credit

%d bloggers like this: