2022-10-27

SwiftUI - Access List Selection in Another View

I want to access the list selection in another view.

import SwiftUI

struct ExerciseSelectorView: View {
    @Environment(\.managedObjectContext) var viewContext
    @Environment(\.dismiss) var dismiss
    @FetchRequest(sortDescriptors: []) var exercises: FetchedResults<Exercise>
    @State var selectedItems = Set<Exercise>()
   
    var body: some View {
        NavigationView {
            
            VStack {
                Button("Add") {
                createExerciseSet()
                }
                List(selection: $selectedItems) {
                    ForEach(exercises, id: \.self) { e in
                        Text(e.exercisename)
                    }
                }
                .environment(\.editMode, .constant(EditMode.active))
                .navigationBarTitle(Text("Selected \(selectedItems.count) rows"))
                .toolbar { EditButton() }
                
            }
            
        }
    }

I'm pretty sure selectedItems can't be a @State var, but when I set it to Binding, the error is "No exact matches in call to initializer" When I try to set it to @ObservedObject, the error is "Generic struct 'ObservedObject' requires that 'Set' conform to 'ObservableObject'" So I'm not sure how to handle an array of a class. I just want to be able to use the array of selectedItems in a different view. Thank you in advance!!!!

Below is the second view where I want to use the selectedItems, but I am getting "Cannot find 'selectedItems' in scope"

import SwiftUI

struct ExSetView: View {
    
    @Environment(\.managedObjectContext) var viewContext
    @Environment(\.dismiss) var dismiss
    @FetchRequest(sortDescriptors: []) var exsets: FetchedResults<ExerciseSet>
    
    var body: some View {
        NavigationView {
            VStack (alignment: .leading) {
                ForEach(selectedItems) { e in
                    
                    NavigationLink(
                        destination: ExSetInputView(selectedItems: e),
                        label: {
                            Text(e.exercise.exercisename)
                        }
                    )}
            }
            
            
        }
        
    }
}

UPDATE:

import SwiftUI

struct ExSetView: View {
    
    @Environment(\.managedObjectContext) var viewContext
    @Environment(\.dismiss) var dismiss
 FetchedResults<ExerciseSet>
    @State var selectedItems = Set<Exercise>()
    
    var body: some View {
        NavigationView {
            VStack (alignment: .leading) {
               
                  Text("Set Count: \(selectedItems.count)")
         }
      }
}


No comments:

Post a Comment