gpt4 book ai didi

ios - SwiftUI使用 View 模型模式以两种不同方式打开 View

转载 作者:行者123 更新时间:2023-12-01 21:58:57 24 4
gpt4 key购买 nike

我需要打开一个名为RequestDetails的 View 。

在两种情况下都可以打开此 View 。

  • 提供数据以打开此请求
  • 提供对Firestore文档
  • 的引用

    在这种情况下,我没有此特定请求的所有详细信息,但仅引用了Firestore文档。我使用此引用在此 View 出现后立即进行查询,并获取有关此请求的详细信息。 RequestDetail(reference: reference)
    class RequestViewModel: ObservableObject {
    @Published var request: RequestModel?
    @Published var requestReference: DocumentReference?

    init(request: RequestModel? = nil, requestReference: DocumentReference? = nil) {
    self.request = request
    self.requestReference = requestReference
    }

    func loadRequest() {
    FirestoreService().fetchDocument(documentReference: self.requestReference) { (request: RequestModel) in
    DispatchQueue.main.async {
    self.request = request
    }
    }
    }

    }

    struct RequestDetails: View {
    @State var reference: DocumentReference?
    @State var request: RequestModel?

    @ObservedObject var vm: RequestViewModel

    var body: some View {
    VStack {
    if request != nil {
    Text(self.request?.senderFirstName)
    }
    }.onAppear {
    if self.vm.package == nil {
    self.vm.loadRequest()
    }
    }
    }
    }

    struct Home: View {
    var request: RequestModel
    var reference: DocumentReference

    var body: some View {
    VStack {
    RequestDetail(request: request)
    RequestDetail(reference: reference)
    }
    }
    }

    问题是我遇到了很多错误,并且想知道背后的逻辑是否正确。我是否以正确的方式使用 View 模型模式?

    最佳答案

    以下内容适合遵循MVVM概念

    struct RequestDetails: View {
    @ObservedObject var vm: RequestViewModel

    var body: some View {
    VStack {
    if self.vm.request != nil {
    Text(self.vm.request!.senderFirstName)
    }
    }.onAppear {
    if self.vm.request == nil {
    self.vm.loadRequest()
    }
    }
    }
    }

    struct Home: View {
    var request: RequestModel
    var reference: DocumentReference

    var body: some View {
    VStack {
    RequestDetail(vm: RequestViewModel(request: request))
    RequestDetail(vm: RequestViewModel(reference: reference))
    }
    }
    }

    关于ios - SwiftUI使用 View 模型模式以两种不同方式打开 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60714263/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com