我在NavigationView中有一个带有食谱的列表,该列表导航到RecipeDetail,只是食谱的详细视图。列表的声明如下:
NavigationView{
List {
Section(header: HStack {
Text("Rezepte")
Spacer()
self.addButton
.sheet(isPresented: self.$showingAddRecipeView) {
AddRecipe { recipe in
self.recipeStore.addRecipe(recipe: recipe)
self.recipeStore.showingAddRecipeView = false
}
}
}) {
ForEach(recipeStore.recipes){ recipe in
NavigationLink(
destination: RecipeDetail(
recipe: self.$recipeStore.recipes[self.recipeStore.recipes.firstIndex(where: { self.recipeStore.selectedRecipe?.id == $0.id }) ?? 0],
creating: false,
addRecipe: nil,
dismiss: nil
).environmentObject(self.recipeStore),
tag: recipe,
selection: self.$recipeStore.selectedRecipe
) {
Card(recipe: recipe)
}.accessibility(identifier: recipe.name)
}
.onMove(perform: moveRecipes)
.onDelete(perform: deleteRecipes)
}
self.roomThemperatureSection
self.importButton
self.exportButton
// self.donateButton
self.aboutButton
}
.listStyle(GroupedListStyle())
.navigationBarTitle("BrotApp", displayMode: .automatic)
.navigationBarItems(trailing: EditButton().padding())
如果我尝试删除自打开应用程序以来未单击的食谱,它就可以正常工作,但是如果我尝试单击并通过标准导航视图“后退”按钮向后导航后以相同手势删除该食谱,则崩溃以下错误:
Fatal error: Index out of range: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift, line 444 2020-06-22 10:27:19.798276+0200 BackApp[1604:40700] Fatal error: Index out of range: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.2.25.8/swift/stdlib/public/core/ContiguousArrayBuffer.swift, line 444
这是删除配方的代码:
func deleteRecipes(at offsets: IndexSet){
for index in offsets {
recipeStore.deleteRecipe(at: index)
}
}
func deleteRecipe(at index: Int) {
if index < recipes.count {
selectedRecipe = nil
DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
self.recipes.remove(at: index)
}
//select next
#if os(macOS)
if recipes.count > 1{
guard let lastRecipe = recipes.last else { return }
selectedRecipe = lastRecipe
}
#endif
}
}