This works fine and redraws the view when the Observable Object updates. I have now added a GeometryReader within this variable in the class. Now, any data items within the Geometry Reader no longer update when the view is rebuilt, following a change in the @Published Value in the Observable Object.
Below is a test View demonstrating this. It is a simple button incrementing the published value on the object. The View body also includes the testObject.resultsView which is an AnyView type summarising the results from the class.
Code Block struct ContentView: View { @ObservedObject var testObject: TEST = TEST() var body: some View { VStack { Text("Current Value From View \(testObject.testValue)") Button<Text>(action: {self.testObject.testValue += 1}, label: { Text("Add One Button")}) testObject.resultView } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
This is my class, including the resultsView variable.
Code Block class TEST: ObservableObject { @Published var testValue: Double = 0 var resultView: AnyView { AnyView( VStack{ Spacer() Text("Text From Object, Outside of GeometryReader") Text("Value \(self.testValue.description)") GeometryReader { geom in VStack { Text("Text From Object Inside Geom Reader") Text(self.testValue.description).frame(width: geom.size.width / 2, height: geom.size.height / 2) }.background(Color.secondary) }}.background(Color.yellow) ) } // End of resultView } //End of Class }
When I run this all values update on the button press, except the one that is returned in the GeometryReader section of the AnyView variable. It seems anything I put in the Geometry reader section no longer updates.
I have also tried passing as a () -> AnyView closure and using a @ViewBuilder function with the same result. It is being called to update as the first return of the value is updating but not the value from within the GeometryReader.
Any Ideas?
I tried all sorts of things including using @ViewBuilder for the variable and with a function to return the view but the problem remained. Adding AnyView(...) to enclose the elements in the GeometryReader was the only way I found to make it work.
Code Block class TEST: ObservableObject { @Published var testValue: Double = 0 var resultView: AnyView { AnyView (VStack{ Text("Text From Object, Outside of GeometryReader") Text("Value \(self.testValue.description)") GeometryReader { geom in AnyView( -> AnyView added to enclose code within GeometryReader VStack{ VStack { Text("Text From Object Inside Geom Reader") Text(self.testValue.description).frame(width: geom.size.width / 2, height: geom.size.height / 3) }.background(Color.secondary) } ) -> Close of AnyView added } -> End of GeomReader } ) } } // End of class