@malc Thanks! To be honest, I forgot about this thread. I had to recall this issue from a year ago :)
Yeah, it makes sense now.
Just to be sure that I understood this correctly - the issue is that myVar's getter is never called by the View's body, and thus body doesn't refresh on its updates (and it makes sense now why that additional Text() fixed this issue).
And .sheet references external state (from the parent view) that isn’t part of the isPresented binding, so changes to myVar won’t automatically affect the sheet’s presentation unless they cause body to be re-evaluated.
And, given this, another solution (yours works great as well) that works would be to create a new View used by the .sheet with its own State& Binding variables, etc.
// ContentView body:
.sheet(isPresented: $presentSheet) {
MySheetView(myVar: $myVar)
}
// Additional View:
struct MySheetView: View {
@Binding var myVar: Int
var body: some View {
// ... (something that uses myVar getters)
VStack {
if myVar == 0 {
Text("The value is nil")
} else {
Text("The value is 1")
.onAppear {
print(myVar) // prints 1
}
}
Text("The value is \(myVar)")
}
}
}
Now, myVar's change will invalidate MySheetView, causing it to be re-evaluated. Plus, either way, it's better to do it this way from a modularization perspective.
Now, for the last part, quoting @Engineer :
Since SwiftUI is declarative rather than procedural, and .onAppear performs its action asynchronously, I don’t think the value of myVar is guaranteed to match its outer context.
It definitely makes sense why the .onAppear used to give a different value (and this is actually why I used it; to check myVar's actual value). Now the answer is complete; I wasn't understanding why the .sheet wasn't being refreshed in the process.
Can you confirm that I understood this correctly? Thanks a lot!
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: