How I can make my View-Extension update View with State input in SwiftUI?

Viewed 291

Here I got an extension which works fine for updating itself at lunch, but after Lunch or Appear, it does not reports the change of data to its View.

My Goal: I want my Extension get sensitive to value that is reporting.

import SwiftUI

struct ContentView: View {
    
    @State var changeString: String = "Hello, world!"
    
    var body: some View {

        customText().stringOfText(changeString).padding()
        
        Button("change") { changeString = "Omid" }.padding()
        
        Text(changeString).padding()
        
  
    }
}



struct customText: View {
    

    
    @State var stringOfText = ""
    
    var body: some View
    {
        Text(stringOfText)
            
    }
}


extension customText {
    func stringOfText(_ text: String) -> customText {
        customText(stringOfText: text)
    }
}
1 Answers

It should not be state inside, because state is not recreated, ie. you need

struct customText: View {
    var stringOfText: String = "" // << here !!
    
    var body: some View {
        Text(stringOfText)
    }
}
Related