How to use @Binding

Asked on 08/08/2024

2 searches

To use @Binding in SwiftUI, you can follow these steps:

  1. Define a State Property: In the parent view, define a state property that will hold the value you want to bind.

  2. Pass the Binding: Pass a binding of this state property to the child view.

  3. Use the Binding: In the child view, use the @Binding property wrapper to create a two-way reference to the state property in the parent view.

Here's a simple example to illustrate:

Parent View

import SwiftUI

struct ParentView: View {
    @State private var rating: Int = 0

    var body: some View {
        VStack {
            Text("Rating: \(rating)")
            RatingView(rating: $rating)
        }
    }
}

Child View

import SwiftUI

struct RatingView: View {
    @Binding var rating: Int

    var body: some View {
        HStack {
            Button(action: {
                rating -= 1
            }) {
                Text("-")
            }
            Text("\(rating)")
            Button(action: {
                rating += 1
            }) {
                Text("+")
            }
        }
    }
}

In this example:

  • The ParentView has a state property rating.
  • The RatingView receives a binding to this state property via $rating.
  • The RatingView can then read and modify the rating value, and these changes will be reflected in the ParentView.

For more detailed information, you can refer to the SwiftUI essentials session from WWDC 2024.