SwiftUI 更新 observedObject in Cell View of list

SwiftUI update observedObject in Cell View of list

我试图更改 observedObject 的值。该值会改变但不会永久改变。当我向下滚动并向后滚动时,该值将变回原始值。我猜是列表的单元格视图中@State 的问题。但我无法弄清楚在 observedObject 中永久更改数据的解决方案。那么我应该怎么做才能通过使用数据单元格永久更改数据。

struct ContentView: View {
    @ObservedObject var dataClass = DataClass()
    var body: some View {
        List(dataClass.data){ item in
            DataCell(item: item)
        }
    }
}
struct DataCell: View {
    @State var item : DataModal
    var body: some View{
        HStack{
            Text("\(item.num!)")
            Text("\(item.val!)").onTapGesture {
                item.val = 1
            }

        }
        .padding(.vertical, 100)
    }
}
struct DataModal : Identifiable {
    var id = UUID()
    var num : Int?
    var val : Int?
}
class DataClass : ObservableObject {
    @Published var data = [DataModal]()
    init(){
        load()
    }
    func load(){
        data = [DataModal(num: 1, val: 1),DataModal(num: 2, val: 2),DataModal(num: 3, val: 3),DataModal(num: 4, val: 4),DataModal(num: 5, val: 5),DataModal(num: 6, val: 6),DataModal(num: 7, val: 7),DataModal(num: 8, val: 8),DataModal(num: 9, val: 9),DataModal(num: 10, val: 10),DataModal(num: 11, val: 11),DataModal(num: 12, val: 12),DataModal(num: 13, val: 13)]
    }
}

你传了一个DataModal的副本,因为它是一个值类型。在这种情况下,您需要将绑定传递到 dataClass 内的原始值,例如

struct ContentView: View {
    @ObservedObject var dataClass = DataClass()
    var body: some View {
        List(dataClass.data.indices, id: \.self){ index in
            DataCell(item: $dataClass.data[index])
        }
    }
}

struct DataCell: View {
    @Binding var item : DataModal
    var body: some View{
        HStack{
            Text("\(item.num!)")
            Text("\(item.val!)").onTapGesture {
                item.val = 1
            }

        }
        .padding(.vertical, 100)
    }
}