Home > Software engineering >  How to update value in previous screen in SwiftUI?
How to update value in previous screen in SwiftUI?

Time:05-21

i am navigating from one screen to another and passing data using @Binding but I am alo trying to update value back to first screen when its updating in second screen.

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)
        }
    }
}

I want to change value in SecondView without dismissing overlay need updated value that in first view.

I am not sure how should i do same in reverse.

CodePudding user response:

You are quite close.

Just add a buttons in the second view to increment the value

struct SecondView: View {
    
    @Binding var valueToGet: Int
    
    var body: some View {
        VStack {
            
            Text("Show value \(valueToGet)")
            Button("Increment") {
                valueToGet  = 1
            }
        }
    }
}
  • Related