Im using the new SwiftUI. I have a UserUpdate
class which is a Bindable Object
and I want to modify these variables and automatically Update the UI.
I update these Values successfully but the views in my UI struct isn't updating when I change the variable in the UserUpdate
class.
It only changes when I modify the @EnviromentObject
variable in the UI struct itself.
That's my Bindable Object Class:
final class UserUpdate: BindableObject {
let didChange = PassthroughSubject<Any, Never>()
var allUsers: [User] = [] {
didSet {
print(allUsers)
didChange.send(allUsers)
}
}
var firstName: String = "" {
didSet {
didChange.send(firstName)
}
}
var lastName: String = "" {
didSet {
didChange.send(lastName)
}
}
}
That's my User class:
struct User: Identifiable {
let id: Int
let firstName, lastName: String
}
Here's how I configure my UI:
struct ContentView : View {
@EnvironmentObject var bindableUser: UserUpdate
var body: some View {
NavigationView {
VStack(alignment: .leading) {
Text("All Users:").bold().padding(.leading, 10)
List {
ForEach(bindableUser.allUsers) { user in
Text("\(user.firstName) \(user.lastName)")
}
}
}
}
}
}
Here I modify the variables in UserUpdate
:
class TestBind {
static let instance = TestBind()
let userUpdate = UserUpdate()
func bind() {
let user = User(id: userUpdate.allUsers.count, firstName: "Heyy", lastName: "worked")
userUpdate.allUsers.append(user)
}
}