Reputation: 788
I'm trying to quick access a list with favourite items from the master view with a modal sheet. The favourite objects are kept in an EnvironmentObject
array. In the modal sheet there is a button, where you can basically add/remove the object from the favourites list. However, when you remove an item, the EnvironmentObject
gets empty and the app crashes:
Thread 1: Fatal error: No
ObservableObject
of typeFavouritesList
found.
In the log it says:
A
View.environmentObject(_:)
forFavouritesList
may be missing as an ancestor of this view.: file
How do I ensure it goes back to the ContentView
naturally?
import SwiftUI
struct ContentView: View {
@EnvironmentObject var favouriteList: FavouritesList
@State private var presentingSheet = false
var body: some View {
NavigationView {
List {
NavigationLink(destination: JudgementsView()) {
Text("Judgements")
}
NavigationLink(destination: SecondaryView()) {
Text("Secondary acts")
}
ScrollView(.horizontal, showsIndicators: false) {
VStack {
if favouriteList.items.isEmpty {
Text("Nothing favoured")
} else {
ForEach(favouriteList.items, id: \.self) { id in
VStack {
HStack {
ForEach(judgementsTAXraw.filter {
$0.id == id
}) { judgement in
NavigationLink(destination: FileViewer(file: judgement.id)) {
Button(judgement.title) {
self.presentingSheet = true
}.sheet(isPresented: self.$presentingSheet) {
ModalSheet(file: judgement.CELEX)
}
}
}
}
HStack {
ForEach(secondaryTAXraw.filter {
$0.id == id
}) { secondary in
NavigationLink(destination: FileViewer(file: secondary.id)) {
Text(secondary.title).padding()
}
}
}
}
}
}
}
}
}
.navigationBarTitle(Text("Test"))
}
}
}
struct ModalSheet: View {
var file: String
@State private var showCopySheet = false
@EnvironmentObject var favouriteList: FavouritesList
var body: some View {
NavigationView {
Text("Modal").navigationBarItems(trailing:
Button(action: {
self.showCopySheet = true
}) {
Image(systemName: "doc.on.doc").frame(minWidth: 40)
}.actionSheet(isPresented: $showCopySheet) {
ActionSheet(title: Text("What do you want to do?"), buttons: [
.destructive(Text("favText"), action: {
if let index = self.favouriteList.items.firstIndex(of: self.file) {
self.favouriteList.items.remove(at: index)
} else {
self.favouriteList.items.append(self.file)
}
}),
.cancel()
])
}.frame(minWidth: 50)
)
}
}
}
Upvotes: 1
Views: 2865
Reputation: 1233
I think you need to pass your favouriteList to ModalSheet like environmentObject try
ModalSheet(file: judgement.CELEX).environmentObject(favouriteList)
Upvotes: 5