【问题标题】:Swift(UI) Error: Cannot use mutating member on immutable value: 'self' is immutableSwift(UI)错误:不能在不可变值上使用变异成员:'self'是不可变的
【发布时间】:2020-10-23 06:07:25
【问题描述】:

基本上我想要做的是如果你按下按钮然后条目应该得到一个新的 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
    }
}

【问题讨论】:

    标签: swift swiftui mutable


    【解决方案1】:

    视图在 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()
              }
          }
       }
    }
    

    【讨论】:

    • 感谢您的快速回答。
    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多