UIKit和SwiftUI下实现点击Shake动画

1周前 27次点击 来自 SwiftUI

在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)))
    }
}
Card image cap
开发者雷

尘世间一个小小的开发者,每天增加一些无聊的知识

本站文章全部采用 CC BY 4.0 协议,欢迎转载

技术文档 >> 系列应用 >>
热推应用
Let'sLearnSwift
学习Swift的入门教程
PyPie
Python is as good as Pie
标签