SwiftUI 代码将一个对象数据分配给数组中的所有其他对象?

SwiftUI code assigns one object data to all other objects in array?

我正在尝试构建一个记事卡应用程序,目前我正在处理用户可以输入记事卡的屏幕。一切正常,除了当我输入一个记事卡的术语和定义时,它会更新所有其他记事卡,以便它们具有相同的术语和定义。 非常感谢您的帮助,不胜感激!:)

import SwiftUI

struct Notecard: Identifiable
{
    let id = UUID()
    let term2: String
    let def2: String
}
class Notecards: ObservableObject
{
   @Published var Notecardsarray = [Notecard]() //stores an array of the notecard items into a single object
}
struct ContentView: View{
    @ObservedObject var notecardobject = Notecards()
    @State private var term = "dfs"
    @State private var def = "df"

    var body: some View {
        NavigationView{
        List{
            ForEach(notecardobject.Notecardsarray){item in
                HStack{
                    TextField("enter term", text: self.$term)
                    TextField("enter definition", text: self.$def)
                }
            }
            .onDelete(perform: removeItems)
        }
    .navigationBarTitle("Notecards")
      .navigationBarItems(trailing:
          Button(action: {
            let newnotecard = Notecard(term2: self.term, def2: self.def)
              self.notecardobject.Notecardsarray.append(newnotecard)
          }) {
              Image(systemName: "plus")
          }
      )
        }

    }
   func removeItems(at offsets: IndexSet) {
       notecardobject.Notecardsarray.remove(atOffsets: offsets)
   }
}
//this will not actually be part of the app that goes to app store
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

我认为问题是,就在这里,您正在传递状态变量 self.$termself.$def,其中它们是 dfs 和 df。相反,您应该使用 item.term2item.def2,因为它在您的 ForEach

List{
    ForEach(notecardobject.Notecardsarray){item in
        HStack{
            TextField("enter term", text: self.$term)
            TextField("enter definition", text: self.$def)
        }
    }
    .onDelete(perform: removeItems)
}

修改后的代码:

 List{
    ForEach(notecardobject.Notecardsarray){item in
        HStack{
            TextField("enter term", text: item.$term2)
            TextField("enter definition", text: item.$def2)
        }
    }
    .onDelete(perform: removeItems)
}

编辑:我在你的例子中没有看到 TextView 结构,但如果它需要数据绑定,你需要将 def2term2 指定为 @State 并使它们成为 var 而不是 let。因为它们现在将作为状态发送到其他视图,所以您还需要 $ 表示数据绑定。我对上面的代码进行了编辑。

修改后的代码:

struct Notecard: Identifiable
{
    let id = UUID()
    @State var term2: String
    @State var def2: String
}

当您在 ForEach 循环中需要 Binding 时,您需要遍历索引而不是元素。

通过使 term2def2 可变来更新 Notecard

struct Notecard: Identifiable {
    let id = UUID()
    var term2: String
    var def2: String
}

通过更改 ForEach 循环更新了 ContentView

ForEach(notecardobject.Notecardsarray.indices, id: \.self){ index in
    HStack{
        TextField("enter term", text: self.$notecardobject.Notecardsarray[index].term2)
        TextField("enter definition", text: self.$notecardobject.Notecardsarray[index].def2)
    }
}