Reputation: 79
The following code is simplified and isolated. It is intended to have a Text()
view, which shows the number of times the button has been clicked, and a Button()
to increment the text view.
The issue: Clicking the button does not actually change the Text() view, and it continues to display "1"
struct Temp: View {
@State var h = struct1()
var body: some View {
VStack {
Button(action: {
h.num += 1
}, label: {
Text("CLICK ME")
})
Text(String(h.num))
}
}
}
struct struct1 {
@State var num = 1
}
What's funny is that the same code works in swift playgrounds (obviously with the Text()
changed to print()
). So, I'm wondering if this is an XCode specific bug? If not, why is this happening?
Upvotes: 1
Views: 513
Reputation: 29242
Remove @State
from the variable in struct1
SwiftUI wrappers are only for SwiftUI View
s with the exception of @Published
inside an ObservableObject
.
I have not found this in any documentation explicitly but the wrappers conform to DynamicProperty
and of you look at the documentation for that it says that
The view gives values to these properties prior to recomputing the view’s body.
So it is implied that if the wrapped variable is not in a struct
that is also a SwiftUI View
it will not get an updated value because it does not have a body
.
https://developer.apple.com/documentation/swiftui/dynamicproperty
The bug is that it works in Playgrounds but Playground seems to have a few of these things. Likely because of the way it complies and runs.
Upvotes: 1