SwiftUI: Get notified when @Binding value changes

I wrote a view to create a typewriter effect in SwiftUI - when I pass in a binding variable it works fine the first time, e.g.: TypewriterTextView($textString)

However, any subsequent time the textString value changes it will not work (since the binding value isn't directly being placed in the body). Am interested in any ideas on how to manually be notified when the @Binding var is changed within the view.

struct TypewriterTextView: View {

    @Binding var textString:String
    @State private var typingInterval = 0.3
    @State private var typedString = ""

    var body: some View {
        Text(typedString).onAppear() {
            Timer.scheduledTimer(withTimeInterval: self.typingInterval, repeats: true, block: { timer in

                if self.typedString.length < self.textString.length {
                    self.typedString = self.typedString + self.textString[self.typedString.length]
                }
                else { timer.invalidate() }
            })
        }
    }
}


Read more here: https://stackoverflow.com/questions/58363563/swiftui-get-notified-when-binding-value-changes

Content Attribution

This content was originally published by ohsnapy at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: