Aatrox11
Aatrox11

Reputation: 65

SwiftUI update observedObject in Cell View of list

I tried to change the value of the observedObject. The value will changed but not permanently. When I scroll down and scroll back, the value will changed back to original value. I guess is the problem of @State in the cell view of list. But I cant figure out what the solution to change the data permanently in observedObject. So what should I do to change the data permanently by using the data cell.

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)]
    }
}

Upvotes: 1

Views: 699

Answers (1)

Asperi
Asperi

Reputation: 258365

You pass a copy of DataModal, because it is a value type. In this scenario you need to pass binding to original value inside dataClass, like

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)
    }
}

Upvotes: 1

Related Questions