Reputation: 55
Starter question: I'm trying to get a View to update after variables included in the array [Member] do change. Pressing the button in the code below does not do anything. After reading many similar topics I know this can not work, but I have no idea how solve it.
import SwiftUI
class Member: Identifiable, ObservableObject {
var id = UUID()
@Published var value:Int
init(value:Int) {
self.value = value
}
}
class Values:ObservableObject {
@Published var v1:Int = 1
@Published var v2:Int = 2
@Published var v3:Int = 3
}
struct ContentView: View {
var values = Values()
var items: [Member]
init() {
items = [Member(value: values.v1), Member(value: values.v2), Member(value: values.v3)]
}
var body: some View {
VStack {
HStack {
ForEach(items) {i in
Text("Value: \(i.value)")
}
}
Button("Change v2 = 0") {
values.v2 = 0
}
}
}
}
Upvotes: 0
Views: 700
Reputation: 4245
I think this is what you're trying to do...
struct Member: Identifiable {
var id = UUID()
var value: Int
}
class Values: ObservableObject {
@Published var items = [Member]()
init() {
items = [Member(value: 1), Member(value: 2), Member(value: 3)]
}
}
struct ContentView2: View {
@ObservedObject var values = Values()
var body: some View {
VStack {
HStack {
ForEach(values.items) { item in
Text("Value: \(item.value)")
}
}
Button("Change 2nd index = 0") {
values.items[1].value = 0
}
}
}
}
Upvotes: 1