Change the text of Text view in SwiftUI

Let's say I have created a Text view. How can I change its text later in the code? Can I use a @State property as the source for the Text view?

struct ContentView: View {
      var body: some View {
            Text("Hello World!")
                 .onTapGesture {
                     // How can I change its text?
            }
      }
}

1 answer

  • answered 2020-03-25 13:38 Chris

    yes you can! try this:

    struct ContentView: View {
    
        @State var text = "Hallo"
    
        var body: some View {
            Text(text)
                .onTapGesture {
                    self.text = "changed"
            }
        }
    }