Created
April 16, 2022 06:48
-
-
Save chriseidhof/7f89fca84d6b6c3acd9d7c6d6ff1259c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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