简体   繁体   中英

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

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

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)

I think that you are doing some mistakes in your code (if your case is a master - detail app)

  • Detail view will contain Element object ( item form your fetched list )

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)
   }
  }
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM