0

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.

irrbloss
  • 207
  • 2
  • 9
  • 2
    You might want to google "SwiftUI animations", there are plenty of examples out there. You will need a state-change, but you can just use the `.onAppear` modifier to change the state immediately at view launch. – HunterLion May 25 '23 at 16:27

1 Answers1

1

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
            }
        }
    }
}
ChrisR
  • 9,523
  • 1
  • 8
  • 26