gpt4 book ai didi

swift - 如何附加到 SwiftUI 中的数组?

转载 作者:行者123 更新时间:2023-11-28 05:38:39 24 4
gpt4 key购买 nike

在 SwiftUI 中追加到数组时遇到问题。

我正在使用 Xcode 11 beta 7 并使用更新的 ObservableObjectEnvironmentObjectPublished 语法 < strong>在 watchOS 应用程序上。 WKHostingController 需要具体类型,因此无法传递 ContentView().environmentObject(subject)

此行使应用程序崩溃:

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

最佳答案

有两种可能的方法:

  1. Using AnyView
class HostingController: WKHostingController<AnyView> {
override var body: AnyView {
return AnyView(AddSubjectView().environmentObject(SubjectDataEnv()))
}
}

result

这是输出(我在按钮中附加了一个 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)

注意新的 👌🏻☺️ 主题。

  1. Injecting the @EnvironmenObject in a "parent view"
class HostingController: WKHostingController<ContentView> {
override var body: ContentView {
return ContentView()
}
}
struct ContentView: View {
var body: some View {
return AddSubjectView().environmentObject(SubjectDataEnv())
}
}

后者会产生相同的结果。

关于swift - 如何附加到 SwiftUI 中的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57729659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com