我有一个视图和一个 viewModel,当用户添加到用户数组时应该更新 ListView。我可以验证是否正在添加用户,但 ObservedObject 没有更新。
我有一个搜索栏,可让您搜索用户,然后更新 ViewModel 中的用户数组,该数组应该更新 View 但它没有。
视图模型
class UsersViewModel: ObservableObject {
@Published var users: [User] = []
@Published var isLoading = false
var searchText: String = ""
func searchTextDidChange() {
isLoading = true
API.User.searchUser(text: searchText) { (users) in
self.isLoading = false
self.users = users
}
// confirmed that users has data now at this point
}
}
看法
struct UsersView: View {
@ObservedObject var usersViewModel = UsersViewModel()
var body: some View {
VStack() {
SearchBarView(text: $usersViewModel.searchText, onSearchButtonChanged: usersViewModel.searchTextDidChange)
// Not getting called after usersViewModel.users gets data
if (usersViewModel.users.count > 0) {
Text(usersViewModel.users[0].username)
}
}
}
}