SwiftUI导航边栏更新时重置

pkwftd7m  于 2023-04-10  发布在  Swift
关注(0)|答案(1)|浏览(120)

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

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

elcex8rz1#

您只能有一个详细级别NavigationLink s,因此您可以将AddItemView的链接设置为不详细,如下所示:

NavigationLink("nav to next") {
            AddItemDetailView()
        }
        .isDetailLink(false)

相关问题