Tuesday, October 01, 2024

What is the role of @State and @Binding in SwiftUI?

 In SwiftUI, @State and @Binding are property wrappers that manage data flow and state changes in views.

@State

@State is used to declare a source of truth for a view's state. It creates a mutable state property that can be changed within the view.

Characteristics:

  • Owned by the view.
  • The initial value is set by the view.
  • Changes trigger view updates.

Use cases:

  • Local state management.
  • Simple forms.
  • Toggle buttons.

Example:

struct CountNumberView: View {

    @State private var number = 0

    

    var body: some View {

        Button("Increment") {

            number += 1

        }

        Text("number: \(number)")

    }

}



@Binding


@Binding is a two-way connection between a view's property and an external source of truth.

Characteristics:

  • References an external state.
  • Changes update the external state.
  • External changes update the view.
Use cases:
  • Parent-child view communication.
  • Shared state between views.
  • Complex forms.

Example:


struct ChildView: View {

    @Binding var name: String

    

    var body: some View {

        TextField("Enter name", text: $name)

    }

}


struct ParentView: View {

    @State private var name = ""

    

    var body: some View {

        ChildView(name: $name)

        Text("Name: \(name)")

    }

}


Key differences

1. Ownership: @State owns the state, while @Binding references external state.
2. Direction: @State is one-way (view-only), while @Binding is two-way (view-external).
3. Updates: @State updates trigger view updates while @Binding updates trigger external state changes.

No comments:

Create a list in SwiftUI with sticky section headers

 Sample Code import SwiftUI struct ContentView : View {     @State var isCustomViewControllerDisplayed = false     @State private va...