1

I have a List view created from an integer array called data and use binding to pass the data to the view. I am using withAnimation when appending elements to the data array.

If the property wrapper of data is @State, shown below, then the animation will be played correctly when appending elements:

struct MyApp: App {
    @State var data: [Int] = Array(1...5)
    
    var body: some Scene {
        WindowGroup {
            ContentView(data: $data)
        }
    }
}

However, If I place the data array into a class conforms to ObservableObject, the animation will not be played at all when appending elements:

class MyData: ObservableObject {
    @Published var data: [Int] = Array(1...5)
}

struct MyApp: App {
    @ObservedObject var data: MyData = MyData()
    
    var body: some Scene {
        WindowGroup {
            ContentView(data: $data.data)
        }
    }
}

Questions

  1. Is my code correct? Or is it a bug of SwiftUI?
  2. In the second situation, how can I correctly show the animation when appending to the array using ObservableObject?

ContentView.swift

struct ContentView: View {
    @Binding var data: [Int]
    
    var body: some View {
        List {
            Button {
                withAnimation {
                    data.append(data.count + 1)
                }
            } label: {
                Text("Append an Item")
            }
            ForEach(data, id: \.self) { number in
                Text(String(number))
            }
        }
    }
}
F5Soft
  • 11
  • 1

1 Answers1

0

try the following code :

class TestViewModel : ObservableObject{
    @Published var data: [Int] = Array(1...5)
}

struct TestView: View {
    
    @StateObject
    var vm = TestViewModel()
    
    var body: some View {
        List {
            Button {
                withAnimation {
                    vm.data.append(vm.data.count + 1)
                }
            } label: {
                Text("Append an Item")
            }
            ForEach(vm.data, id: \.self) { number in
                Text(String(number))
            }
        }
    }
}
Osman
  • 1,496
  • 18
  • 22