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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With