Home > other >  SwiftUI: Doesn't pass data from selected list item into detail view
SwiftUI: Doesn't pass data from selected list item into detail view

Time:06-27

I have been trying to show selected item's detail view but can't seem to get it working. When trying to get the name of the item into the detail view by diaries.name I get an error Value of type '[DiaryItem]' has no member 'name'

ForEach(diaries.items) {item in
NavigationLink(destination: DiaryDetailView(diaries: diaries)) {
     HStack {
     VStack(alignment: .leading) {
     Text(item.name)
    .font(.headline)
    }
               Spacer()
                        
  } //: HSTACK
 }//: FOR
}

And here is the detail view

struct DiaryDetailView: View {
    
    let diaries: Diaries
    
    var body: some View {
        VStack {
            Text(diary.name)
        }
}
}
struct DiaryDetailView_Previews: PreviewProvider {
    static var previews: some View {
        DiaryDetailView(diaries: Diaries())
    }
}

And my class where it saves the form information

class Diaries: ObservableObject {
    @Published var items = [DiaryItem]() {
        didSet {
            if let encoded = try? JSONEncoder().encode(items) {
                UserDefaults.standard.set(encoded, forKey: "Items")
            }
        }
    }

    init() {
        if let savedItems = UserDefaults.standard.data(forKey: "Items") {
            if let decodedItems = try? JSONDecoder().decode([DiaryItem].self, from: savedItems) {
                items = decodedItems
                return
            }
        }

        items = []
    }
}
struct DiaryItem: Identifiable, Codable {
    var id = UUID()
    let name: String
    let fishName: String
    let info: String
}

CodePudding user response:

you probably wanted something like this:

ForEach(diaries.items) {item in
NavigationLink(destination: DiaryDetailView(diary: item)) { // <-- here
     HStack {
     VStack(alignment: .leading) {
     Text(item.name)
    .font(.headline)
    }
               Spacer()
                        
  } //: HSTACK
 }//: FOR
}

struct DiaryDetailView: View {
    let diary: DiaryItem  // <-- here
    
    var body: some View {
        VStack {
            Text(diary.name)
        }
}
}

and

struct DiaryDetailView_Previews: PreviewProvider {
    static var previews: some View {
        DiaryDetailView(diary: DiaryItem(name: "name1", fishName: "fish1", info: "info1"))
    }
}
  • Related