边栏更新时重置 SwiftUI 导航

问题描述 投票:0回答:0

更改侧边栏中的状态将重置导航

我希望将我保存的数据用作侧边栏中的选择,但是当我尝试将数据添加到核心数据时,侧边栏将重置状态并将我带回根导航。是否可以保持导航状态?

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)")
        }
    }
}

swift swiftui core-data navigation sidebar
© www.soinside.com 2019 - 2024. All rights reserved.