SwiftUI: detecting when @State variable has change in their @Binding

3.9k views Asked by At

I'm trying to figure how can change the value from different View. Here is the implementation of my main view:

import SwiftUI
import Combine

struct ContentView: View {
    @State private var isPresented: Bool = false
    
    @State private var textToProces = "" {
        didSet{
            print("text: oldValue=\(oldValue) newValue=\(textToProces)")

        }
    }
    var body: some View {
       
        ZStack{
            VStack{
                Button("Show Alert"){
                    self.isPresented = true
                }.background(Color.blue)
            }
            ItemsAlertView(isShown: $isPresented, textToProcess: $textToProces)
        }
    }
}

On this view I'm trying to change the textToProces variable:

struct AnotherView: View {
    
    @Binding var isShown: Bool
    @Binding var textToProcess: String

    var title: String = "Add Item"
    let screenSize = UIScreen.main.bounds
    
    var body: some View {
        VStack {
            Button(action: {
                self.textToProcess = "New text"
                self.isShown = false
            }, label: {
                Text("dissmis")
            })
            Text(self.textToProcess)
        }
        .background(Color.red)
        .offset(y: isShown ? 0 : screenSize.height)
    }
}

When I change the value on this line self.textToProcess = "New text" the textToProcess in the main view never gets the notification of the change. What I can I do to get the notification of the change in the main view any of you knows?

I'll really appreciate your help

1

There are 1 answers

0
KevinP On BEST ANSWER

You have to use the onChange modifier to track changes to textToProces.

import SwiftUI
import Combine

struct ContentView: View {
    @State private var isPresented: Bool = false
    
    @State private var textToProces = ""

    var body: some View {
       
        ZStack{
            VStack{
                Button("Show Alert"){
                    self.isPresented = true
                }.background(Color.blue)
            }
            ItemsAlertView(isShown: $isPresented, textToProcess: $textToProces)
        }
        .onChange(of: textToProces) { value in
            print("text: \(value)")
        }
    }
}