skip to Main Content

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

}

2

Answers


  1. 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)

    Login or Signup to reply.
  2. 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)
       }
      }
     }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search