[英]I cannot pass my object to another view with NavigationLink in SwiftUI
In my home view, I can see listName and date.在我的主页视图中,我可以看到列表名称和日期。 Also, I can see productCount when I write elements.productCount, but I cannot see my productCount and listName when I go another view另外,当我写 elements.productCount 时,我可以看到 productCount,但是当我写 go 另一个视图时,我看不到我的 productCount 和 listName
HomeView主视图
@StateObject var homeData = HomeViewModel()
// Fetching Data.....
@Environment(\.managedObjectContext) var context
@FetchRequest(entity: ShoppingList.entity(), sortDescriptors: [NSSortDescriptor(key: "date", ascending: true)],animation: .spring()) var results : FetchedResults<ShoppingList>
var body: some View {
VStack{
NavigationView{
NavigationLink(destination: DetailView(list: homeData)){
ForEach(results){ element in
VStack(alignment: .leading) {
Text("\(element.listName!)")
.font(.headline)
.foregroundColor(.black)
.padding(.top, 20)
DetailView详细视图
struct DetailView: View {
@ObservedObject var list = HomeViewModel()
var body: some View {
Text("\(list.productCount)")
}
} }
You should not create initiate list
in DetailView
, because you pass it from home view - only declare it, so like您不应该在DetailView
中创建启动list
,因为您是从主视图传递它的 - 只声明它,就像
struct DetailView: View {
@ObservedObject var list: HomeViewModel // << here !!
Btw, it looks strange that you put all ForEach
into one NavigationLink (is it intended? that might bring you problems later)顺便说一句,将所有ForEach
放入一个 NavigationLink 看起来很奇怪(是故意的吗?以后可能会给您带来问题)
I think that you are doing some mistakes in your code (if your case is a master - detail
app)我认为您在代码中犯了一些错误(如果您的案例是master - detail
应用程序)
Element
object ( item form your fetched list )详细视图将包含Element
object(您获取的列表中的项目)like that:像那样:
struct DetailView: View {
var element: Element
var body: some View {
Text("\(element.listName)")
}
}
And your home view:以及您的主视图:
NavigationView{
ForEach(results){ element in
NavigationLink(destination: DetailView(element: element)){
VStack(alignment: .leading) {
Text("\(element.listName!)")
.font(.headline)
.foregroundColor(.black)
.padding(.top, 20)
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.