SwiftUI @State vs Binding

前端 未结 6 1696
野的像风
野的像风 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:22

    Think of State as the single source of truth for your view, as a means of mutating a variable & invalidating the view to reflect that state.

    Binding on the other hand, is a two-way connection between a view and its underlying model. A means of mutating a State that is not managed by the view (for example a Toggle that reflects and controls a bool value that the control itself has no knowledge about its storage or origin)

    Finally, you can get a Binding from any State by using the $ prefix operator.

    A simple guide for choosing between them would be:

    Do I need to modify a value that is private to me? => State

    Do I need to modify a State of some other view? => Binding

提交回复
热议问题