https://stackoverflow.com/questions/77022165/why-occur-animation-effect-in-swiftui
Why occur animation effect in SwiftUI
I posted a question on Stack Overflow. There's clearly no reason for the Rectangle below to run a color-changing animation.
But a color-changing animation kept showing up, so I looked into it,
and sometimes it was frozen every time I launched the app, and sometimes the Rectangle on top froze instead, so I figured out it was just a bug.
The problem is how often this bug happens.
struct ContentView: View { var randColor: Color { Color(red: randomNumber/255, green: randomNumber/255, blue: randomNumber/255) } @State var isAnimation = false var randomNumber: Double { return Double.random(in: 0...255) } var body: some View { VStack { Rectangle() .fill(isAnimation ? randColor : .red) .frame(width: 200, height: 200) .onAppear { withAnimation(.easeIn(duration: 1).repeatForever(autoreverses: true)) { isAnimation = true } } BottomRectangle() } } }
I wondered how to fix this, and I was able to fix it with the animation modifier.
Pass the Animation() object that you'd put in withAnimation straight into the animation modifier,
and make the change happen in onAppear(perform:), that is, set isAnimation = true, and I confirmed it works as intended in almost every case.
struct ContentView: View { var randColor: Color { Color(red: randomNumber/255, green: randomNumber/255, blue: randomNumber/255) } @State var isAnimation = false var randomNumber: Double { return Double.random(in: 0...255) } var body: some View { VStack { Rectangle() .fill(isAnimation ? randColor : .red) .frame(width: 200, height: 200) .animation(.easeIn(duration: 1).repeatForever(autoreverses: true), value: isAnimation) .onAppear { isAnimation = true } // Change!! BottomRectangle() } } }