Amazing article. I wonder if I could ask some rudimentary questions about the following excerpt: " Hive now has an ID and a binding in the same way as the flowers do. You are using a let of type Binding instead of an @Binding property because you don’t need this view to be recomputed when the value changes. You’re only interested in sending the results of a tap up to the parent view."
I am wondering if you (or anyone) can elaborate on the following:
I’ve been experimenting to understand what you mean about using @Binding only being required if you need a view to be recomputed when the value changes, but am still not clear. I’ve been swapping @Binding with let Binding and it seems to have the same effect. Can you shed any further light on this?
I was also wondering if you can shed any light on using a let over a var in this context? What benefits does it have? I’ve always used a var with @Binding without a second thought.
It’s really about Swift syntax and how SwiftUI uses it. @Binding is the convenient function wrapper version, and it lets you treat the property as a standard var with a value. Then you can use the value directly in a view.
The special part is that the @Binding can be changed from somewhere else outside the view, and the view will treat it just like it does a @Statevar.
Even better is that you can pass that binding into another function or view. Behind that simple syntax it creates a new instance of a type Binding. This type has the mechanism for 2 way communication. So you can pass it through to a function in order to provide a way for the function to set the binding value. The bound value, once set by the function, will then make its way back to the origin of the binding.
So, with Hive: Hive takes a Binding<Int> which is to say when hive is tapped, send that Int to the Binding. Hive has no idea what the binding is, or where it came from, nor does it care :). Hive doesn’t use it in its body at all, so we make it clearer in code that it’s purely procedural.
Notice how the parent view has an @State var selectedTargetID, and then when the hive view is created it’s passed as the binding, using the $ character:
That’s a convenient way for a child view to update a value on a parent view.
Great article and discussion. I was trying to make the bee go back to the original position of CGPoint(x: 75, y: 100), by changing the frames, but after many attempts I am still unsuccessful. Anyone has any ideas?