How to pass / communicate data from one view to another using @Binding in SwiftUI?

struct FirstView: View {
    @State private var valueToPass : Int = 0
    var body: some View {
        VStack {
            Button(action: {
                self.valueToPass += 1
            }) {
                Text("Increase value \(self.valueToPass)")
            }
        }
        .overlay(
            SecondView(valueToGet: $valueToPass)
        )
    }
}
      
struct SecondView: View {
    @Binding var valueToGet: Int
    var body: some View {
        VStack {
            Text("Show value \(valueToGet)")
                .padding(.top, 50)
        }
    }
}

Even if we change value any view it will update in for both the view

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s