我试图将数据传递到ViewModel中,并得到“从初始化返回而不初始化所有存储的属性”
在ViewModel中的init(entry:Entry)之后,我所做的任何事情都会得到错误。
我首先是这样从MainView传递数据的:
struct MainView: View {
@State var entry = Entry()
// inputting the data
TextField("Beg Value", text: self.$entry.a)
// passing to next view
NavigationLink(
destination: ShowView( entry: entry ),
label: {Image(systemName: "arrow.clockwise") })
}
这是获取数据的视图。
struct ShowView: View {
var entry: Entry
@ObservedObject var showVM: ShowViewModel
init( entry:Entry ) {
self.entry = entry
self.showVM = ShowViewModel( entry: entry )
}
}
还有初始化数据后出现错误的ViewModel。我尝试了很多变体。
class ShowViewModel: ObservableObject {
var entry: Entry
init(entry: Entry) {
self.entry = entry
}
init(){
print("here") \\ Return from initializer without initializing all stored properties
}
}
和入口结构。我也上过课。
struct Entry {
var month: Date = Date()
var a:String = "1"
var b:String = "2"
var c:String = "3"
var d:String = "4"
var e:String = "5"
var f: String = ""
}
谢谢。
答案 0 :(得分:0)
删除第二个init
并设置一个默认值(如果未在参数中提供,则使用默认值),例如
class ShowViewModel: ObservableObject {
@Published var entry: Entry
init(entry: Entry = Entry()) {
self.entry = entry
}
}
答案 1 :(得分:0)
这是工作代码。
我想您忘了在MainView中添加NavigationView了,而Body丢失了。
此外,可以使用@Binding代替@ObservedObject。
struct Entry {
var month: Date = Date()
var a:String = "1"
var b:String = "2"
var c:String = "3"
var d:String = "4"
var e:String = "5"
var f: String = ""
}
class ShowViewModel: ObservableObject {
var entry: Entry
init(entry: Entry) {
self.entry = entry
}
}
struct ShowView: View {
@ObservedObject var showVM: ShowViewModel
init( entry:Entry ) {
self.showVM = ShowViewModel( entry: entry )
}
var body: some View {
Text(showVM.entry.a)
}
}
struct MainView: View {
@State var entry = Entry()
var body: some View{
NavigationView{
VStack {
// inputting the data
TextField("Beg Value", text: self.$entry.a)
.textFieldStyle(RoundedBorderTextFieldStyle())
// passing to next view
NavigationLink(
destination: ShowView( entry: entry ),
label: {Image(systemName: "arrow.clockwise") })
}.padding()
}
}
}