Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created April 16, 2022 06:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseidhof/7f89fca84d6b6c3acd9d7c6d6ff1259c to your computer and use it in GitHub Desktop.
Save chriseidhof/7f89fca84d6b6c3acd9d7c6d6ff1259c to your computer and use it in GitHub Desktop.
//
// ContentView.swift
// Shared
//
// Created by Chris Eidhof on 16.04.22.
//
import SwiftUI
struct Jump: AnimatableModifier {
var progress: Double = 0
var amplitude: CGFloat = 20
var animatableData: Double {
get { progress }
set { progress = newValue }
}
func body(content: Content) -> some View {
// We only jump for the first half of the animation, after that we stay in place
let jumpProgress = progress < 0.5 ? progress * 2 : 1
content.offset(y: -sin(.pi * jumpProgress) * amplitude)
}
}
extension View {
func jump(_ active: Bool, amplitude: CGFloat = 20) -> some View {
modifier(Jump(progress: active ? 1 : 0, amplitude: amplitude))
}
}
struct ContentView: View {
@State var active = false
var body: some View {
Text("Hello, world!")
.jump(active)
.animation(.linear(duration: 2).repeatForever(autoreverses: false), value: active)
.padding(50)
.onAppear {
active = true
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment