SwiftUI · State & Binding: Part 1 | raywenderlich.com

@modnar please see the completed project for updated code which fixes an issue with layout priority yet again. This is built from that:

image

I just commented out the .layoutPriority(1) line for the Spacer() which is the last line in the ZStack and it rendered as shown in the video.

1 Like

Awesome! Thanks for letting me know. Laurie.

As I’m trying to fully understand this: the @State attribute declares the ‘Model’ properties as being mutable and re-renders its own Parent view when state changes correct? So I’m a little confused by using the @Binding attribute, if @State is declared in the Parent View with @Binding declared in the Child views, is the model being made mutable with the @Binding attribute, if so, why do I need the @State attribute in the Parent view? Am I understanding this wrong? Is the @State attribute required to be declared before the @Binding attribute can be declared in the Child Views? Sorry if that is seems confusing…I’m new to SwiftUI

Am I missing something here? Are posts no longer being reviewed in here?

@txpilot03 you’re not missing something, I was on a break for a week - my apologies. State is the absolute source of truth (in this case where the data is kept hold of in the parent). When we need a child to have the ability to mutate that source of truth, we pass it in as a binding, otherwise it would simply copy the value at that moment and only update if we toggled the state in some other way.

State will always change, even if its in a child view which mutates it, the point is that the source of the state is always located in one place. In imperative code you can find yourself with multiple sources of truth and there are so many little bugs caused by this. The fact your passing it in keeps that flow clear, but you can still toggle the state, and all reliant views will be udpated as a result.

Thanks for the question! Laurie.