在NavigationLink的嵌套NavigationView中列出CoreData对象的正确方法



在xcode 12(swift 5.3(中,我使用条件导航链接导航到另一个导航视图,用导航链接列出coreData对象。但AnotherView的NavigationTitle似乎无法正确显示在屏幕顶部,而是填充到顶部。另一个导航视图中的列表具有外部白色背景色。我要传递给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")
}
}
}

您不需要第二个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

最新更新