我在我的ViewModel文件中有一个函数,它将数据添加到数组中,我可以在我的ViewModel文件中打印出该数组并查看所有数据。但在视图文件中,当我调用数组时,比如viewModel。数组中似乎没有数据。如何更改代码以访问视图中的数组?此外,fetchConvos()函数在init中被调用,因此用户数组应该得到更新。
视图模型文件
class MessageViewModel: ObservableObject{
@Published var users = [User]()
func fetchConvos(){
service.getConversations() { users in
self.users = users
}
}
视图
@ObservedObject var viewModel = MessageViewModel()
var body: some View {
if let index = viewModel.users.firstIndex(of: user) {
....
因为users数组是空的,所以index永远不会被分配。
您必须订阅@Published属性包装器。因此,您使用.onReceive(
.
为了让事情更清楚,这里有一个带注释的小例子:
class MessageViewModel: ObservableObject{
@Published var users = [String]()
func fetchConvos() {
self.users = ["Name 1", "Name 2"]
}
}
struct ContentView: View {
@ObservedObject var viewModel = MessageViewModel()
@State var name: String = ""
var body: some View {
Text(name)
// onReceice is to subscribe to @Published property wrappers
.onReceive(viewModel.$users, perform: { users in
name = users.first ?? "No users!"
})
.onAppear { // when the view appears we creating our users in the model, thanks our onReceive subscription, we can adapt our views justs by changing the @State property wrapper
viewModel.fetchConvos()
}
// This button changes the view itself
Button {
changeName()
} label: {
Label("Give the user a new name", systemImage: "plus")
}
.buttonStyle(.bordered)
// onChange is for subscribing to @State property wrappers
.onChange(of: name) { newValue in
let newName = newValue
print("new user name:", newName)
viewModel.users[0] = newName // here we notify the model, that the view changed
#warning("Make sure the users array is not empty")
}
}
func changeName() {
name = "New name"
}
}