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
- Is my code correct? Or is it a bug of SwiftUI?
- 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))
}
}
}
}