Home > Back-end >  How to delay animation in SwiftUI?
How to delay animation in SwiftUI?

Time:04-09

I want to animate two Text fields, the second with a delay. But it is not working, there is no delay, they animate at the same time from position 100 to 0.

Here is the code:

@State private var offset: CGFloat = 100
@State private var offset2: CGFloat = 100
@State private var duration = 0.4
@State private var duration2 = 0.4
@State private var opacity = 0.0
@State private var opacity2 = 0.0

VStack(alignment: .leading) {
                          Text("select exercise")
                    .foregroundColor(.gray)
                    .font(.system(size: 36))
                    .fontWeight(.bold)
                    .opacity(opacity)
                    .offset(x: 0.0, y: offset)
                       .onAppear {
                           withAnimation(.easeInOut(duration: duration)) { self.offset = 0
                               self.opacity = 1
                           }
                        }
                Text("00 reps")
                    .foregroundColor(.gray)
                    .font(.system(size: 36))
                    .fontWeight(.bold)
                    .opacity(opacity2)
                    .offset(x: 0.0, y: offset2)
                       .onAppear {
                           withAnimation(.easeInOut(duration: duration2)) { self.offset2 = 0
                               self.opacity2 = 1
                           }
                        }
                    }
                }

What am I missing ?

CodePudding user response:

From the partial code you provided it seems you are manipulating the same variables in both closures. Change that to individual ones for each field.

Reason:

when you do:

@State private var changeVar = 0.0

withAnimation(...){
       changeVar = 1.0
   }

SwiftUI will change that value incrementally from the value it is at the moment the animation starts to the value provided in the closure. As soon as the value changes the view gets redrawn with the current value of changeVar. As you use the same var for both Views the changes are applied to both at the same time. Hence the animation starts for both at the same time.

  • Related