【问题标题】:The correct way to list CoreData object in nest NavigationView in NavigationLink在 NavigationLink 的嵌套 NavigationView 中列出核心数据对象的正确方法
【发布时间】:2020-08-19 09:48:00
【问题描述】:

在 xcode 12 (swift 5.3) 中,我使用条件 navigationLink 导航到另一个 navigationView 以使用 NavigationLink 列出 coreData 对象。但似乎 AnotherView 的 NavigationTitle 无法正确显示在屏幕顶部,而是填充到顶部。另一个 navigationView 中的列表具有外部白色背景色。我想传递给SomethingView 的something.id 报告Argument passed to call that takes no arguments 错误,但我可以在Text 中得到something.name。

struct StartView: View {
    @State var changeToAnotherView: String? = nil
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                ...
                NavigationLink(destination: AnotherView(), tag: "AnotherView",
                               selection: $changeToAnotherView) { EmptyView() }
            }
        }
    }
}

struct AnotherView: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Something.entity(), sortDescriptors: []) var somethings: FetchedResults<Something>
    ...
    var body: some View {
        NavigationView {
            List {
                ForEach(self.somethings, id: \.id) { something in
                    NavigationLink(destination: SomethingView(somethingID: something.id)) {
                        Text(something.name ?? "unknown name")
                    }
                }
            }
            .navigationBarTitle("SomethingList")
        }
    }
}

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    你不需要第二个NavigationView - 它必须只是视图层次结构中的一个,并且最好通过引用传递CoreData对象(视图将能够观察它),所以

    struct AnotherView: View {
        @Environment(\.managedObjectContext) var moc
        @FetchRequest(entity: Something.entity(), sortDescriptors: []) var somethings: FetchedResults<Something>
        ...
        var body: some View {
            List {
                ForEach(self.somethings, id: \.id) { something in
                    NavigationLink(destination: SomethingView(something: something)) {
                        Text(something.name ?? "unknown name")
                    }
                }
            }
            .navigationBarTitle("SomethingList")
        }
    }
    
    struct SomethingView: View {
       @ObservedObject var something: Something
    
       var body: some View {
    
       // .. your next code
    

    【讨论】:

    • 非常感谢。似乎something: something 也报告了相同的no arugment 错误。如何将选择的内容传递给SomethingView_Previews: PreviewProvider?.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多