【发布时间】:2021-08-16 15:03:28
【问题描述】:
我想在MainView 中显示一个单独的SubjectView。
SubjectView 中subject 上的属性topics 不可访问。
我该怎么办?谢谢。
更新:
ForEach(subject.topics, id: \.self) { topic in
Text(topic.title)
}
...可能是有问题的部分。
文件:SubjectView
import SwiftUI
struct SubjectView: View {
@State var subject: Subject
var body: some View {
List {
ForEach(subject.topics, id: \.self) { topic in
Text(topic.title)
}
}
}
}
文件MainView
import SwiftUI
struct MainView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Subject.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Subject.name, ascending: true)]) var subjects: FetchedResults<Subject>
@State var subjectName: String = ""
var body: some View {
NavigationView {
Form {
List {
ForEach(subjects, id: \.self) { subject in
NavigationLink(
destination: SubjectView(subject: subject),
label: {
Text(subject.name ?? "-")
})
}
}
}
.navigationTitle("Schulfächer")
}
}
}
Screenshot of the Subject entity
SubjectView:var body: some View 处的错误为:
Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the project
【问题讨论】:
-
你应该显示
Subject。 -
主题由 XCode 创建
-
不相关但
@StateinSubjectView没有意义。@State用于值类型,@StateObject用于引用类型。但由于这个对象实际上不是 真相的来源 并且无论如何都是引用类型,所以只需声明let subject: Subject -
@vadian,谢谢!