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

问题描述 投票:0回答:1

我正在努力在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)开发的新手,所以我不确定。

ios arrays swift append swiftui
1个回答
0
投票

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

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

现在,我们可以声明行为符合预期的相关视图

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]收到显示消息[Test.Student(id:D1410829-F039-4D15-8440-69DEF0D55A26,名称:“”),Test.Student(id:50D45CC7-8144-49CC-88BE-598C890F2D4D,名称:“”)]

© www.soinside.com 2019 - 2024. All rights reserved.