Conditional reaction to update a Binding value in onChange in SwiftUI?

Viewed 186

I am updating State value in 2 Views via State and Binding, my goal is that onChange would fire to work only if the update happens from ContentView, I already using this down code for this job, it works but I have to use an extra Variable for this job, I want to know if there is any better way of doing this work with more advanced and better way, also I am not interested to using combine for this.

struct ContentView: View {
    @State private var stringValue: String = "Hello"

    var body: some View {

        Text(stringValue).padding()

        Button("update stringValue from ContentView") { 
           stringValue += " updated from ContentView!" 
        }

        TextView(stringValue: $stringValue)
    }
}

struct TextView: View {
    @Binding var stringValue: String
    @State private var internalStringValue: String = String()

    var body: some View {
        Text(stringValue).padding()
            .onChange(of: stringValue) { newValue in
                if newValue != internalStringValue { 
                    print("stringValue updated!") 
                }
            }

        Button("update stringValue from TextView") {
            internalStringValue = stringValue + " updated from TextView!"
            stringValue = internalStringValue
        }
    }
}
0 Answers
Related