UIView shake animation

后端 未结 16 1306
梦毁少年i
梦毁少年i 2020-11-28 18:07

i\'m trying to make a UIView shake when a button is pressed.

I am adapting the code I found on http://www.cimgf.com/2008/02/27/core-animation-tutorial-window-shake-e

16条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 18:59

    Swift 3 implementation based on @Mihael-Isaev answer

    private enum Axis: StringLiteralType {
        case x = "x"
        case y = "y"
    }
    
    extension UIView {
        private func shake(on axis: Axis) {
            let animation = CAKeyframeAnimation(keyPath: "transform.translation.\(axis.rawValue)")
            animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
            animation.duration = 0.6
            animation.values = [-20, 20, -20, 20, -10, 10, -5, 5, 0]
            layer.add(animation, forKey: "shake")
        }
        func shakeOnXAxis() {
            self.shake(on: .x)
        }
        func shakeOnYAxis() {
            self.shake(on: .y)
        }
    }
    

提交回复
热议问题