我有一个存储在 CoreData
中的项目列表和一个右上角的添加按钮,用于将项目添加到列表并以编程方式导航到 ItemView
。
当列表中没有项目并且我按下添加按钮时,创建的项目会按预期滑入,但 NavigationLink
不会自动导航到其 ItemView
。此外,NavigationLink
在点击它时甚至不起作用。
仅当再次按下添加按钮时(在第二项中滑动),NavigationLinks
才会按预期开始工作。
重现步骤:
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@State private var selection: Date?
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
var body: some View {
NavigationView {
List {
ForEach(items) { item in
NavigationLink(
"Item at \(item.timestamp!, formatter: itemFormatter)",
destination: ItemView(item: item),
tag: item.timestamp!,
selection: $selection
)
}
.onDelete(perform: deleteItems)
}
.listStyle(InsetGroupedListStyle())
.navigationTitle("Items")
.toolbar {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
selection = newItem.timestamp
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
struct ItemView: View {
let item: Item
var body: some View {
Text("Item at \(item.timestamp!, formatter: itemFormatter)")
}
}
private let itemFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
return formatter
}()
答案 0 :(得分:0)
我在 0.5 秒后异步更新选择,错误消失了。不确定这是否是一个可靠的解决方案,但从用户的角度来看,首先看到项目滑入并在之后导航是很直观的。
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
selection = newItem.timestamp
}