如何使用BindableObjects(EnviromentObject)? [英] How to use BindableObjects (EnviromentObject)?
问题描述
我正在使用新的SwiftUI.我有一个 UserUpdate
类,它是一个 Bindable Object
,我想修改这些变量并自动更新UI.
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.
我成功更新了这些值,但是当我更改 UserUpdate
类中的变量时,我的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.
当我在UI结构本身中修改 @EnviromentObject
变量时,仅会更改.
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)
}
}
}
那是我的User类:
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)")
}
}
}
}
}
}
在这里我修改 UserUpdate
中的变量:
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)
}
}
推荐答案
我发现我必须从UI调用该方法才能使其正常工作,因此它可以在同一流上使用.
I found out that I had to call the method from my UI to get it working so its on the same stream.
例如:
struct ContentView : View {
@EnvironmentObject var networkManager: NetworkManager
var body: some View {
VStack {
Button(action: {
self.networkManager.getAllCourses()
}, label: {
Text("Get All Courses")
})
List(networkManager.courses.identified(by: \.name)) {
Text($0.name)
}
}
}
}
这篇关于如何使用BindableObjects(EnviromentObject)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!