我试图快速访问一个列表与最喜欢的项目,从主视图与一个模态表。喜欢的对象保存在EnvironmentObject
数组中。在模态表中有一个按钮,基本上可以从收藏列表中添加/删除对象。但是,当您删除一个项目时,EnvironmentObject
将为空,应用程序崩溃:
线程1:致命错误:没有找到类型为
FavouritesList
的ObservableObject
。
日志上写着:
作为该视图的祖先,
FavouritesList
的View.environmentObject(_:)
可能会丢失.:file
如何确保它自然返回到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)
)
}
}
}
发布于 2020-01-06 19:49:30
我认为你需要把你的favouriteList像environmentObject一样传递给ModalSheet
ModalSheet(file: judgement.CELEX).environmentObject(favouriteList)
https://stackoverflow.com/questions/59619439
复制