I'm trying to create a SwiftUI app, and I'm encountering some surprising behavior. I have a background in React.js so I'm familiar with declarative UI systems, but I think that's working against me here because this isn't behaving as I would expect.
So what I'm trying to do with this code is create a button that changes some state values and causes a sheet to open from the bottom of the page and display a value.
struct ExampleView: View {
@State var pageOpen: Bool = false
@State var valueString: String = "Initial Value (you shouldn't see this)"
var body: some View {
NavigationView {
Button(action: {
valueString = "Testing"
pageOpen = true
}) {
Text("Click me")
}
}
.sheet(isPresented: $pageOpen) {
let _ = print("pageOpen is \(pageOpen)")
let _ = print("valueString is \(valueString)")
Text(valueString)
}
}
}
This works the second or third time I run open the sheet, but the first time I click the button, it's like the variables haven't been updated yet. The values printed are still the initial values.
I could reiterate how I think this should work but clearly I'm misunderstanding something.
Edit: I'm using XCode 13, testing in the iOS 15 simulator.