How to make a simple up and down floating animation in SwitfUI?

Viewed 1580

I want to make the text "Hello, World!" float up and down, slowly, without stopping, once the view appears.

import SwiftUI

struct animate: View {
    var body: some View {
        Text("Hello, World!")
    }
}

Thank you!

2 Answers

Updated: Xcode 13.4 / iOS 15.5

Here is possible simple approach. Tested with Xcode 11.4 / iOS 13.4. Of course parameters can be tuned by needs.

demo

struct BoncingView: View {
    @State private var bouncing = false
    var body: some View {
        Text("Hello, World!")
            .frame(maxHeight: .infinity, alignment: bouncing ? .bottom : .top)
            .animation(Animation.easeInOut(duration: 5.0).repeatForever(autoreverses: true), value: bouncing)
            .onAppear {
                self.bouncing.toggle()
            }
    }
}

there are for sure better and more elegant ways to solve it , but one way would be :

struct ContentView: View {


    @State var y : CGFloat = 100
    @State var addThis: CGFloat = 100


    var body: some View {
        Text("Hello, World!")
            .position(x: 100, y: y)
            .onAppear() {
                Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
                    withAnimation() {
                        self.addThis = -self.addThis
                        self.y = self.y + self.addThis
                    }
                }
        }
    }
}
Related