【发布时间】:2020-04-24 10:19:07
【问题描述】:
我正在尝试使用模式表从主视图快速访问包含收藏项目的列表。最喜欢的对象保存在EnvironmentObject 数组中。在模态表中有一个按钮,您基本上可以在其中从收藏夹列表中添加/删除对象。但是,当您删除一个项目时,EnvironmentObject 将变为空并且应用程序崩溃:
线程 1:致命错误:未找到
ObservableObject类型的FavouritesList。
日志中写着:
FavouritesList的View.environmentObject(_:)作为此视图的祖先可能会丢失。:文件
我如何确保它自然地回到ContentView?
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)
)
}
}
}
【问题讨论】: