Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animations higher in the SwiftUI view hierarchy overriding nested animations

Tags:

swift

swiftui

I have a SwiftUI View which has a repeating animation onAppear. When that view is used within a view hierarchy that includes another animation, the higher-level animation overrides the nested one. Consider the following basic example:

struct Example: View {
  @State private var opacity: Double = 0

  var body: some View {
    Text("Example")
      .opacity(opacity)
      .onAppear() {
        withAnimation(Animation.easeInOut(duration: 2).repeatForever(autoreverses: true)) {
          self.opacity = 1
        }
      }
  }
}

When this is used in a context similar to the following, the repeating animation does not run. If I remove the animation from this stack, the repeating animation works as expected.

struct Parent: View {
  var body: some View {
    VStack {
      Example()
    }
    .animation(.easeInOut)
  }
}

How can I structure this to allow both animations to work? When children are added to the VStack they should animate as per that view's animation property, but they should retain their own defined animations too. Is there some documentation on animations and the boundaries between them that I have missed somewhere?

like image 214
James Allardice Avatar asked Sep 16 '25 03:09

James Allardice


1 Answers

You need to link your internal animation to specific state variable, then it will be independent.

Tested with Xcode 12 / iOS 14

  var body: some View {
    Text("Example")
      .opacity(opacity)
      .animation(Animation.easeInOut(duration: 2).repeatForever(autoreverses: true), 
          value: opacity)            // << here !!
      .onAppear() {
          self.opacity = 1
      }
  }
like image 89
Asperi Avatar answered Sep 19 '25 16:09

Asperi