Is there any way I can add animation when elements of a ForEach loop appears or disappears?
I have tried using withAnimation{} and .animation() in many ways but they didn't seem to work
Here is some code (Xcode 11 beta 5):
import SwiftUI
struct test: View {
@State var ContentArray = ["A","B","C"]
var body: some View {
ScrollView{
VStack{
ForEach(ContentArray.indices, id: \.self){index in
ZStack{
// Object
Text(self.ContentArray[index])
.frame(width:100,height:100)
.background(Color.gray)
.cornerRadius(20)
.padding()
//Delete button
Button(action: {
self.ContentArray.remove(at: index)
}){
Text("✕")
.foregroundColor(.white)
.frame(width:40,height:40)
.background(Color.red)
.cornerRadius(100)
}.offset(x:40,y:-40)
}
}
}
}
}
}
#if DEBUG
struct test_Previews: PreviewProvider {
static var previews: some View {
test()
}
}
#endif
As can be seen below, without animations everything feels super abrupt. Any solution is really appreciated
Important notice: The layout should change in the same way List does when the number of elements changes. For example, every object automatically moves top when a top object is deleted