Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI @State vs Binding

Tags:

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<*>.

If I understood it correctly, Binding is just technically State but it doesn't update the view. If that is the case then why would I need Binding if I could just use State to do the same thing?

like image 597
Archie G. Quiñones Avatar asked Dec 09 '19 10:12

Archie G. Quiñones


People also ask

What is difference between binding and state in SwiftUI?

Indicate data dependencies in a view using state, and share those dependencies with other views using bindings. The user interface of a SwiftUI app is a composition of views that form a view hierarchy.

What does @state do in SwiftUI?

With @State, you tell SwiftUI that a view is now dependent on some state. If the state changes, so should the User Interface. It's a core principle of SwiftUI: data drives the UI.

What is a SwiftUI binding?

A binding in SwiftUI is a connection between a value and a view that displays and changes it. You can create your own bindings with the @Binding property wrapper, and pass bindings into views that require them.

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.


1 Answers

Both @State and @Binding are property wrappers.

@State

  • It is used to update the value of a variable every time.
  • We can also say it's a two way binding.
  • If we change the property state then SwiftUI will automatically reload the body of the view.
  • It is used for simple properties like strings, integers and booleans.

@Binding

  • Using this, you can access the state property of another view.
  • It will give you the read and write access for the variable.
like image 183
Hetashree Bharadwaj Avatar answered Sep 28 '22 11:09

Hetashree Bharadwaj