How to implement a binding in SwiftUI?

Generated on 8/2/2024

1 search

To implement a 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.

    struct ParentView: View {
        @State private var rating: Int = 0
    
        var body: some View {
            RatingView(rating: $rating)
        }
    }
    
  2. Create a Binding: Pass the state property to the child view using the $ prefix to create a binding.

    struct RatingView: View {
        @Binding var rating: Int
    
        var body: some View {
            VStack {
                Text("Rating: \(rating)")
                Button("Increase Rating") {
                    rating += 1
                }
            }
        }
    }
    

In this example, ParentView has a state property rating, and it passes a binding to RatingView. The RatingView can then read and modify the rating value, and any changes will be reflected back in the ParentView.

For more details, you can refer to the SwiftUI essentials session at WWDC 2024, which discusses how to use bindings to create a two-way reference to the state of another view.