gpt4 book ai didi

ios - Swift Array .append() 方法在 SwiftUI 中不起作用

转载 作者:行者123 更新时间:2023-12-01 21:59:12 24 4
gpt4 key购买 nike

我正在努力在 SwiftUI 中做一个简单的追加。这是我的代码:

// This is defined in my custom view
var newClass = Class()

// This is inside a List container (I hid the Button's content because it doesn't matter)
Button(action: {
self.newClass.students.append(Student())
print(self.newClass.students) // This prints an Array with only one Student() instance - the one defined in the struct's init
})

// These are the custom structs used
struct Class: Identifiable {
var id = UUID()
@State var name = ""
@State var students: [Student] = [Student()] // Right here
}

struct Student: Identifiable {
var id = UUID()
@State var name: String = ""
}

我认为它可能与新的 @Struct 有某种关系。事情,但我是iOS(和Swift)开发的新手,所以我不确定。

最佳答案

让我们稍微修改一下模型...

struct Class: Identifiable {
var id = UUID()
var name = ""
var students: [Student] = [Student()]
}

struct Student: Identifiable {
var id = UUID()
var name: String = ""
}

... 而不是使用 @State在不想要的地方(因为它被设计在 View 内部,而不是模型),让我们引入 View Model 层作为
class ClassViewModel: ObservableObject {
@Published var newClass = Class()
}

现在我们可以声明行为符合预期的相关 View
struct ClassView: View {
@ObservedObject var vm = ClassViewModel()

var body: some View {
Button("Add Student") {
self.vm.newClass.students.append(Student())
print(self.vm.newClass.students)
}
}
}

输出:

Test[4298:344875] [Agent] Received display message [Test.Student(id: D1410829-F039-4D15-8440-69DEF0D55A26, name: ""), Test.Student(id: 50D45CC7-8144-49CC-88BE-598C890F2D4D, name: "")]

关于ios - Swift Array .append() 方法在 SwiftUI 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60581114/

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