UIView shake animation

后端 未结 16 1316
梦毁少年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:53

    Swift 4.0:

    Based on the top answer but a refinement over the animation: This does not have the jumps at the start and end of animation.

        let midX = center.x
        let midY = center.y
    
        let rightAnim = CABasicAnimation(keyPath: #keyPath(CALayer.position))
        rightAnim.duration      = 0.07
        rightAnim.autoreverses  = true
        rightAnim.fromValue     = CGPoint(x: midX, y: midY)
        rightAnim.toValue       = CGPoint(x: midX + 9, y: midY)
    
        let leftAnim = CABasicAnimation(keyPath: #keyPath(CALayer.position))
        leftAnim.duration       = 0.07
        leftAnim.autoreverses   = true
        leftAnim.fromValue      = CGPoint(x: midX, y: midY)
        leftAnim.toValue        = CGPoint(x: midX - 9, y: midY)
    
        let group = CAAnimationGroup()
        group.duration      = leftAnim.duration + rightAnim.duration
        group.animations    = [rightAnim, leftAnim]
        group.repeatCount   = 3
    
        layer.add(group, forKey: #keyPath(CALayer.position))
    

提交回复
热议问题