0

我有MasterView一个列表。
通过单击一个项目,将DetailView显示 。
我正在以标准的 SwiftUI 方式通过NavigationLink.

我将detailStateDetailView 作为参数传递。

我期待在DetailView显示屏幕时,对 的任何更改detailState仍会触发对 DetailView 的更新。
(首先显示“正在加载...”屏幕,然后在完全加载时显示数据)

但这似乎没有发生。
如果detailState值更改,则不会触发视图更新。
(数据完全加载后仍然显示“正在加载...”消息)

struct MasterView: View {
    var state : AppState
    let model : Model
    
    var body: some View {
        NavigationView {
            List {
                Section(header: MasterListHeader(masterState: state.masterState)) {
                    ForEach (state.masterState.itemsList, id: \.nome) { row in
                        NavigationLink(destination: DetailView(detailState: state.detailState)) {
                                MasterRow(row: row, model: model)
                        }
                    }
                }
            }
        }
    }
}


struct DetailView: View {
    var detailState: DetailState
    let model : Model
    
    var body: some View {
        VStack {
            if (detailState.itemDetails.isEmpty) {
                LoadingScreen()
            } else {
                DataScreen()
            }
        }.onAppear {
            model.loadDetailItem(nome: detailState.itemName)
        }
    }
}

这里是定义源对象的地方:

class AppViewModel: ObservableObject {
    let coreModel : Model = Model()
    @Published var appState : AppState = AppState()
    
    init() {
        coreModel.onChange { newState in
            self.appState = newState
        }
    }
}


@main
struct iosApp: App {
    @StateObject var vm = AppViewModel()

    var body: some Scene {
        WindowGroup {
            ContentView(state: vm.appState, model: vm.coreModel)
        }
    }
}

struct ContentView: View {
    var state : AppState
    let model : Model

    var body: some View {
        MasterView(state: state, model: model)
    }
}

什么是最好的设计来确保DetailView对变化做出反应detailState

4

0 回答 0