(SwiftUI 2.0, MacOS App) I want to have a sidebar with a picker that selects the project, and a list below will show which analyses are in that project, and when you click on an analysis, it shows the detail in the view to the right, as shown below. How it should look
My code for this view is shown below. I am using state variables to keep track of which project has been selected by the picker, and then pass that down to the list so it knows what to show. The list then has a navigation link that shows the analysis details.
It works/looks how I need it to, but when I am viewing the details of an analysis in "Project Alpha" and then go and choose another project from the picker without de-selecting the analysis from the current list, I get the dreaded "[SwiftUI] Modifying state during view update, this will cause undefined behavior" error.
I have used various .onAppear and .onChange modifiers to try and get this to stop (as previous forum answers have suggested), without any luck.
Thanks in advance.
import SwiftUI
struct ContentView: View {
@State private var selectedProject: String = "All"
@State var people: People
@State private var peopleInProject: [People] = []
var body: some View {
NavigationView {
VStack {
VStack {
Text("Select Project")
.font(.title)
Picker("", selection: $selectedProject) {
ForEach(people.getProjects(), id: \.self) {project in
Text(project)
.font(.callout)
}
}
.onAppear(perform: {peopleInProject = people.getPeople()})
.onChange(of: selectedProject) {_ in print(selectedProject)
if (selectedProject == "All") {
peopleInProject = people.getPeople()
} else {
peopleInProject = people.getPeople().filter {$0.project == selectedProject}
}
}
.pickerStyle(MenuPickerStyle())
}
List{
ForEach(peopleInProject, id: \.self) {person in
NavigationLink(destination: PersonView(bio: person.bio)) {
Text(person.name)
}
}
}
}
}
}
}