在SwiftUI中追加到数组时遇到问题。
我正在使用 Xcode 11 beta 7 ,并在watchOS应用上使用更新的ObservableObject
,EnvironmentObject
和Published
语法 >。 WKHostingControlle
r需要具体的类型,以便传递ContentView().environmentObject(subject) is not possible
。
此行使应用程序崩溃:
self.subjectData.store.append(Subject(name: self.addedSubject, isFavorite: false))
关于什么是错的任何想法?
struct Subject: Codable, Identifiable {
var id: UUID = UUID()
var name: String
var isFavorite: Bool
}
class SubjectDataEnv: ObservableObject {
@Published var store = [
Subject(name: "Physics", isFavorite: true),
Subject(name: "Science", isFavorite: false)
]
@Published var selectedSubject = Subject(name: "Subject 1", isFavorite: false)
}
class HostingController: WKHostingController<ContentView> {
override var body: ContentView {
return ContentView()
}
}
struct ContentView: View {
@State var subjectData = SubjectDataEnv()
var body: some View {
SubjectView().environmentObject(subjectData)
}
}
struct SubjectView: View {
@EnvironmentObject var subjectData: SubjectDataEnv
var body: some View {
List {
ForEach(subjectData.store) { subject in
NavigationLink(destination: DurationView()
.environmentObject(self.subjectData)
)
}
NavigationLink(destination: AddSubjectView()
.environmentObject(self.subjectData)
) {
Text("+")
}
}
}
}
struct AddSubjectView: View {
@EnvironmentObject var subjectData: SubjectDataEnv
@State var addedSubject: String = "subject"
var body: some View {
VStack(alignment: .leading, spacing: 0) {
TextField("Add your subject", text: $addedSubject)
Button(action: {
self.subjectData.store.append(Subject(name: self.addedSubject, isFavorite: false)) // crashes the app
}) {
Text("Done")
}
}
}
}
答案 0 :(得分:1)
可能有两种方法:
- 使用AnyView
class HostingController: WKHostingController<AnyView> {
override var body: AnyView {
return AnyView(AddSubjectView().environmentObject(SubjectDataEnv()))
}
}
这是输出(我在按钮中附加了print
)
print(self.subjectData.store)
Subject(id: 2F3745EE-752B-4C8C-8A4F-8C21E73B315C, name: "Physics", isFavorite: true)
Subject(id: 5A9CF711-F6BE-4854-8F58-35FD004B2419, name: "Science", isFavorite: false)
Subject(id: E2F6A25E-3BC0-4D17-9AEF-07286533D475, name: "??", isFavorite: false)
Subject(id: 62FA7D12-A3D5-4381-8232-F48268B433F1, name: "☺️", isFavorite: false)
在此处注意新的??
和☺️
主题。
- 在“父视图”中注入
@EnvironmenObject
class HostingController: WKHostingController<ContentView> {
override var body: ContentView {
return ContentView()
}
}
struct ContentView: View {
var body: some View {
return AddSubjectView().environmentObject(SubjectDataEnv())
}
}
后者将产生相同的结果。