-1

我很难理解为什么我必须在调用此视图时提供名为 vm 的弹出视图依赖项,因为它是可观察的

 struct ContentView: View {
        @State private var showPopup1 = false
        var body: some View {
            VStack {
                Button(action: { withAnimation {  self.showPopup1.toggle()}}){
                    Text("showPopup1")  }
                Text("title")
               DetailView()  /// this line shows error
            }
           
        }
    }
    struct DetailView:View {
        @ObservedObject  var vm:ViewModel
        var body : some View {
            Text("value from VM")
            
        }
    }
    class ViewModel: ObservableObject {
        @Published var title:String = ""
        
    }
4

1 回答 1

0

初始化视图时必须设置 vm 属性。这是通常的方式。

struct ContentView: View {
    @State private var showPopup1 = false

    var body: some View {
        VStack {
            Button(action: { withAnimation {  self.showPopup1.toggle()}}){
                Text("showPopup1")  }
            Text("title")

            DetailView(vm: ViewModel()) // Initiate your ViewModel() and pass it as DetailView() parameter
        }
    }
}

struct DetailView:View {

    var vm: ViewModel

    var body : some View {
        Text("value from VM")
    }
}

class ViewModel: ObservableObject {
    @Published var title:String = ""
}

或者你可以使用@EnvironmentObject。您必须将 .environmentObject(yourObject) 传递给要使用 yourObject 的视图,但同样您必须在传递它之前对其进行初始化。

顺便说一句,我不确定这是不是一个好方法,因为您声明 .environmentObject 的视图的所有子视图都可以访问 environmentObject,并且您通常只需要一个 ViewModel 用于一个 View。

struct ContentView: View {
    @State private var showPopup1 = false
    var body: some View {
        VStack {
            Button(action: { withAnimation {  self.showPopup1.toggle()}}){
                Text("showPopup1")  }
            Text("title")

            DetailView().environmentObject(ViewModel()) // Pass your ViewModel() as an environmentObject

        }
    }
}

struct DetailView:View {

    @EnvironmentObject var vm: ViewModel // you can now use your vm, and access it the same say in all childs view of DetailView

    var body : some View {
        Text("value from VM")
    }
}

class ViewModel: ObservableObject {
    @Published var title:String = ""
}
于 2020-11-09T16:41:46.030 回答