Swift(UI) 错误:无法在不可变值上使用变异成员:“self”是不可变的

2024-04-29

基本上我想做的是,如果您按下按钮,那么条目应该获得一个新的 CEntry。如果有人能帮助我那就太好了。谢谢!

struct AView: View {

   var entries = [CEntries]()

   var body: some View {
       ZStack {
           VStack {
               Text("Hello")
               ScrollView{
                   ForEach(entries) { entry in
                       VStack{
                        Text(entry.string1)
                        Text(entry.string2)
                    }
                }
            }
        }
        Button(action: {
            self.entries.append(CEntries(string1: "he", string2: "lp")) <-- Error
        }) {
            someButtonStyle()
        }
    }
}

}


C世纪级

 class CEntries: ObservableObject, Identifiable{
    @Published var string1 = ""
    @Published var string2 = ""

    init(string1: String, string2: String) {
        self.string1 = string1
        self.string2 = string2
    }
}

SwiftUI 中的视图是不可变的。您只能改变它们的状态,这是通过更改具有@State属性包装器:

@State var entries: [CEntries] = []

但是,虽然您可以这样做,但就您而言CEntries是一个类 - 即引用类型 - 所以虽然你可以检测到数组中的变化entries- 添加和删除元素,您将无法检测元素本身的变化,例如当.string1属性已更新。

但这并没有帮助,因为它是一个ObservableObject.

相反,改变CEntries成为一个struct- 值类型,因此如果它改变,值本身也会改变:

struct CEntries: Identifiable {
    var id: UUID = .init()
    var string1 = ""
    var string2 = ""
}

struct AView: View {

   @State var entries = [CEntries]() 

   var body: some View {
       VStack() {
          ForEach(entries) { entry in
             VStack {
                Text(entry.string1)
                Text(entry.string2)
             }
          }
          Button(action: {
            self.entries.append(CEntries(string1: "he", string2: "lp"))
          }) {
              someButtonStyle()
          }
      }
   }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift(UI) 错误:无法在不可变值上使用变异成员:“self”是不可变的 的相关文章

随机推荐