我很难理解为什么在调用这个视图时必须给予名为vm的Popup视图依赖项,因为它是可观察的
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 = ""
}
在初始化视图时,必须设置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(传递到要使用Object的视图,但在传递它之前,您必须对其进行初始化。
顺便说一句,我不确定这是否是一个好方法,因为environmentObject可以访问您在其上声明.environmentObject的视图的所有子视图,并且您通常只需要一个ViewModel来访问一个视图。
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 = ""
}