在ContentView.swift中,我有:
List(recipeData) { recipe in NavigationLink(destination: RecipeView(recipe: recipe)){
Text(recipe.name)
}
}
在RecipeView中,用户可能会更新recipeData变量。但是,当RecipeView关闭时,ContentView不会基于更新的recipeData进行更新。
recipeData不是@State数组,而是在ContentView结构外部声明的普通数组。我不能轻易将其设置为@State变量,因为它已在应用程序的其他部分使用。
谢谢!
答案 0 :(得分:0)
使用@ObservableObject
和@Published
可以满足您的要求。
ViewModel
final class RecipeListViewModel: ObservableObject {
@Published var recipeData: [Recipe] = []
....
....
//write code to fetch recipes from the server or local storage and fill the recipeData
....
....
}
查看
struct RepositoryListView : View {
@ObservedObject var viewModel: RecipeListViewModel
var body: some View {
NavigationView {
List(viewModel.recipeData) { recipe in
NavigationLink(destination: RecipeView(recipe: recipe)) {
Text(recipe.name)
}
}
}
}