'View is not updated using @State property wrapper in SwiftUI
The view does not get updated with using @State wrapper. The view gets updated without using @State wrapper but has to do it manually.
import SwiftUI
struct SwiftUIView: View {
@ObservedObject var people: People
var body: some View {
VStack {
ForEach(people.peoples){ person in
HStack{
Text("\(person.age)")
if person.ismale {
Text("Male")
} else {
Text("Female")
}
Button(action:{ person.age += 1}){
Text("Age+1")
}
}
}
}
}
}
struct Person: Identifiable{
var id = UUID()
@State var age: Int
var ismale = true
}
class People: ObservableObject {
@Published var peoples: [Person]
init() {
self.peoples = [
Person(age: 10),
Person(age: 12, ismale: false)
]
}
}
struct SwiftUIView_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView(people: People())
}
}
For some reason, when the button is clicked there are no changes to the view.
If I change it to
Button(action:{ **self.people.peoples[0].age += 1** }){
Text("Age+1")
}
...
struct Person: Identifiable{
var id = UUID()
**var age: Int**
var ismale = true
}
It updates, but the button would not be dynamic. However, if I do person.age += 1 inside the ForEach loop without the @State wrapper for variable age.
ERROR: "Left side of mutating operator isn't mutable: 'person' is a 'let' constant"
I thought I understand what does Struct, Class, @State mean... I guess not... Thank ahead for any solutions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
