Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding @Binding in SwiftUI

Tags:

swift

swiftui

I watched some WWDC videos and Apple docs about data binding, and according to my current understanding, @State as a property delegate will provide a binding connection between the view and the annotated property, for example:

@State var myText: String

var body: some View {
  VStack {
    TextField($myText, placeholder: Text("input"))
    Text(myText)
  }
}

This will bind myText with the content of the text field I added (i.e. one changes the other will follows up to update)

However, though I know $myText refers to the binding type of Binding, I noticed that Binding is also a property delegate, and I noticed it appears in some code examples from Apple. I have no idea what this is used for as a property delegate. @State already does the binding work, then what do we need @Binding for? Apple docs suck for now about this.

like image 955
Wizard Avatar asked Jun 07 '19 06:06

Wizard


People also ask

What does @binding mean Swift?

@Binding lets us declare that one value actually comes from elsewhere, and should be shared in both places. This is not the same as @ObservedObject or @EnvironmentObject , both of which are designed for reference types to be shared across potentially many views.

What is two way binding in SwiftUI?

Two Way Binding allows the data to be transferred to change the initial look of viewController. If we are interested in creating a button that changes color when the user presses it, we need to state keyword and Two-way binding.

How do I pass a binding variable in SwiftUI?

The best solution here (to my opinion) is custom Bindings with a a wrapper View. That will give you two choices: Bind your (child) View with the parent View so that both parent and child can change the value. Don't bind child View with parent so that ONLY the child will save the value internally.

What is state and binding in SwiftUI?

@State property wrappers are used to read and write variables from a structure. It is used in single view and is recommended that you set its property as private so that other views cannot access it. @Binding property wrappers are used to access variables from other views.


1 Answers

According to this WWDC Talk (Data Flow through Swift UI):

https://developer.apple.com/wwdc19/226

@State should be used for local/private changes inside a View. Ideally, they would be private.

@Binding should be used in subviews/reusable components when the value lives outside the current view domain.

You can see it in presentation(:_) APIs.

There are probably bunch of states inside them, that tell SwiftUI how to display them - but the decision of whether it should appear or not it's up to the superview, hence the @Binding (isShowing) you need to provide.

like image 189
Matteo Pacini Avatar answered Sep 29 '22 16:09

Matteo Pacini