【问题标题】:Swift Array .append() method not working in SwiftUISwift Array .append() 方法在 SwiftUI 中不起作用
【发布时间】:2020-06-20 04:41:29
【问题描述】:

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

【问题讨论】:

  • 如果从Class 的属性中删除@State 会怎样?
  • 试试吧!编译器会抛出一个错误(“Cannot use mutating member on immutable value: 'self' is immutable”),但我认为可以修复。

标签: ios arrays swift append swiftui


【解决方案1】:

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

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

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

...而不是在不想要的地方使用@State(因为它被设计为在视图内部,而不是模型),让我们引入视图模型层作为

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,名称:"")]

【讨论】:

  • 非常感谢!结果我设法通过从Class 中删除@State 使其工作(但不是从Student,因为这会使编译器抛出错误)。它工作正常,万一出现任何问题(这很可能发生),我一定会尝试你的建议!
猜你喜欢
  • 2015-11-24
  • 1970-01-01
  • 2012-10-11
  • 1970-01-01
  • 2021-01-02
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 2018-08-04
相关资源
最近更新 更多