更改侧边栏中的状态将重置导航
我希望在侧边栏中使用我保存的数据作为选择,但当我尝试将数据添加到核心数据时,侧边栏将重置状态并将我带回根导航。是否可以保持导航状态?
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
animation: .default)
private var items: FetchedResults<Item>
var body: some View {
NavigationView {
List {
NavigationLink("Add Item") {
AddItemView()
}
ForEach(items) { item in
NavigationLink {
Text("Item at \(item.timestamp!, formatter: itemFormatter)")
} label: {
Text(item.timestamp!, formatter: itemFormatter)
}
}
}
Text("Select an item")
}
}
}
struct AddItemView: View {
var body: some View {
NavigationLink("nav to next") {
AddItemDetailView()
}
}
}
struct AddItemDetailView: View {
@Environment(\.managedObjectContext) private var viewContext
var body: some View {
Button("add") {
addItem()
}
}
private func addItem() {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
1条答案
按热度按时间elcex8rz1#
您只能有一个详细级别
NavigationLink
s,因此您可以将AddItemView
的链接设置为不详细,如下所示: