Batuhan Baran
Batuhan Baran

Reputation: 47

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

}

Upvotes: 0

Views: 196

Answers (2)

Ouail Bellal
Ouail Bellal

Reputation: 1794

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

Upvotes: 0

Asperi
Asperi

Reputation: 257711

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)

Upvotes: 2

Related Questions