Search code examples
swiftuiswiftui-animation

Animate a view in SwiftUI without a state-variable?


I’m learning SwiftUI right now and have gotten to animations, which so far only seem to work with a state-change by some kind of user interaction.

Is it possible to have a looping animation playing as soon as the view loads? I want to animate some letters bouncing up and down (Image-views or Text-views) as a part of the design. Is this possible with native SwiftUI without different hacks that might stop working when Apple updates the framework?

I’ve also been looking at Rive, but I really wish it would be possible to do directly in SwiftUI.


Solution

  • Following @HunterLion, Just for the fun of it :)

    struct ContentView: View {
        
        @State private var animate = false
        
        var body: some View {
            HStack {
                Text("Up")
                    .offset(y: animate ? -20 : +20)
                Text("and")
                    .offset(y: animate ? +20 : -20)
                Text("Down")
                    .offset(y: animate ? -20 : +20)
                Text("again")
                    .offset(y: animate ? +20 : -20)
            }
            .onAppear {
                withAnimation(.easeInOut.repeatForever(autoreverses: true)) {
                    animate = true
                }
            }
        }
    }