【发布时间】:2021-05-10 22:45:02
【问题描述】:
我有一个存储在CoreData 中的项目列表,右上角有一个添加按钮,用于向列表中添加一个项目并以编程方式导航到ItemView。
当列表中没有项目并且我按下添加按钮时,创建的项目按预期滑入,但NavigationLink 不会自动导航到其ItemView。此外,NavigationLink 甚至在点击它时也不起作用。
只有当再次按下添加按钮时(在第二项中滑动),NavigationLinks 才会开始按预期工作。
重现步骤:
- 创建一个新的 Single View App 并单击 CoreData and Hosted in CloudKit。 CoreData 中应该已经存储了一个 Item Entity。
- 将 ContentView.swift 替换为:
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
}()
- 单击右上角的添加按钮。然后尝试单击 NavigationLink。它不会导航。只有再次按下添加按钮时,它才会按预期工作。
【问题讨论】:
标签: core-data swiftui swiftui-navigationlink