SwiftUI @State vs Binding

前端 未结 6 1594
野的像风
野的像风 2021-02-04 12:43

I am learning iOS Programming with Swift and SwiftUI. I know very little and I am very confuse about the difference between a @State and a Binding<*>

6条回答
  •  臣服心动
    2021-02-04 13:42

    State

    •   @State keyword allows us to ask the SwiftUI to monitor the value of the property. Once the value will change, the View will be invalidated and rendered again in efficient manner.
    •   A persistent value of a given type, through which a view reads and monitors the value.
    •   It is just another @propertyWrapper that outlines a source of truth.
    •   When you use state the framework allocate persistence storage for variable and tracks it as a dependency ... you alway has to specify an initial constant value"
    

    Binding

    •   @Binding and $ prefix allows passing State property into the nested child.
    •   A manager for a value that provides a way to mutate it.
    •   @Binding yet another @propertyWrapper that depends explicitly on state.
    •   By using the Binding property wrapper you define an explicit dependency to a source of truth without owning it, additionally you don't need to specify an initial value because binding can be derived from state.
    

    Link for your reference: https://medium.com/stepstone-tech/swiftui-101-how-to-use-state-and-binding-in-your-first-custom-ui-control-64d395947492

提交回复
热议问题