Skip to content

Instantly share code, notes, and snippets.

@chriseidhof chriseidhof/shake.swift
Last active Oct 1, 2019

Embed
What would you like to do?
//
// ContentView.swift
// Shake
//
// Created by Chris Eidhof on 01.10.19.
// Copyright © 2019 Chris Eidhof. All rights reserved.
//
import SwiftUI
struct Shake: GeometryEffect {
var amount: CGFloat = 10
var shakesPerUnit = 3
var animatableData: CGFloat
func effectValue(size: CGSize) -> ProjectionTransform {
ProjectionTransform(CGAffineTransform(translationX: amount * sin(animatableData * .pi * CGFloat(shakesPerUnit)), y: 0))
}
}
struct ShakeSample: View {
@State var attempts: Int = 0
var body: some View {
VStack {
Rectangle()
.fill(Color.pink)
.frame(width: 200, height: 100)
.modifier(Shake(animatableData: CGFloat(attempts)))
Spacer()
Button(action: {
withAnimation(.default) {
self.attempts += 1
}
}, label: { Text("Login") })
}
}
}
struct Wrong: View {
@State var wrongAttempt: Bool = false
var body: some View {
VStack {
Rectangle()
.fill(Color.pink)
.frame(width: 200, height: 100)
.offset(x: wrongAttempt ? -10 : 0)
.animation(Animation.default.repeatCount(5))
Spacer()
Button(action: { self.wrongAttempt.toggle() }, label: { Text("Login") })
}
}
}
struct ContentView: View {
var body: some View {
ShakeSample()
}
}
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
You can’t perform that action at this time.