UIKit和SwiftUI下实现点击Shake动画


1年前 647次点击 来自 移动端

标签: iOSSwiftUI

在UIKit下实现Shake动画可使用以下代码:

extension UIView {
    /// https://stackoverflow.com/a/34778432
    func shake() {
        let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
        animation.duration = 0.6
        animation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0]
        layer.add(animation, forKey: "shake")
    }
}

而在SwiftUI中则可使用modifier来实现

//1.Shake动画
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))
    }
}
//2.调用
struct PhoneticsCell: View {
    @State var attempts: Int = 0

    var body: some View {
        VStack(alignment: .leading) {
            Text("点我摇摆").onTapGesture {
                withAnimation(.default) {
                    self.attempts += 1
                }
            }
        }.modifier(Shake(animatableData: CGFloat(attempts)))
    }
}

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1