【问题标题】:SwiftU NavigationView: how to update previous view every time coming back from the secondary viewSwiftUI NavigationView:每次从辅助视图返回时如何更新以前的视图
【发布时间】:2019-12-31 05:40:15
【问题描述】:

在 ContentView.swift 中,我有:

List(recipeData) { recipe in NavigationLink(destination: RecipeView(recipe: recipe)){
                        Text(recipe.name)
                     }
                 }

在RecipeView 中,用户可以更新recipeData 变量。但是,RecipeView 关闭时,ContentView 不会根据更新的 recipeData 进行更新。

recipeData 不是@State 数组,而是在 ContentView 结构之外声明的普通数组。我不能轻易将其设为@State var,因为它用于应用程序的其他部分。

谢谢!

【问题讨论】:

  • 我会将recipeData 包裹在@ObservedObject 中(因此使其符合ObservableObject

标签: swift swiftui navigationview


【解决方案1】:

使用@ObservableObject@Published 可以实现您的要求。

视图模型

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)
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多