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



View- just like aUIView. Instead of aVStackhave you tried using aList? I'm pretty sure animations work there. (IIRC, stacks are not views, just a way to order views.)UIKit) then you may well be limited there. IMHO, aListis almost like aUITableView. Next, a "hierarchy" of views (think aButtonwith aVStackfor it's label) gets "automagically" shrunk into a singleViewby SwiftUI. But a "stack" of Views? I really thought I saw things to suggest that's separate views in a... stack. (Hope I'm wrong.) You can use animations to make a view "appear" - offset, slide, easeInOut. - but that seems overkill. Good luck!