This question already has answers here:
How do you make a shake animation for a button using Swift 3 [closed]

(2个答案)


3年前关闭。




我正在学习使用关键帧和 Spring 动画的UIView动画,并且试图在点击它后使按钮摇动。问题是我从库中拖放了按钮,并将后缘固定到其上方的UILabel上,而没有别的。在各个示例中,我看到了标题约束,但是我的按钮没有标题。这是我到目前为止的代码
@IBAction func noButtonPressed(_ sender: UIButton) {
    UIView.animate(withDuration: 1, delay: 1, usingSpringWithDamping: 0.5, initialSpringVelocity: 15, options: [], animations: {
        self.noButtonTrailing.constant = 16
        self.view.layoutIfNeeded()
    })
}

我是否应该在某个地方进行 header 约束?谢谢

最佳答案

这是线性运动和UIView阻尼动画的简单媒体计时动画。

注意:Swift 4

extension UIView {


    // Using CAMediaTimingFunction
    func shake(duration: TimeInterval = 0.5, values: [CGFloat]) {
        let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")

        // Swift 4.2 and above
        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)

        // Swift 4.1 and below
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)


        animation.duration = duration // You can set fix duration
        animation.values = values  // You can set fix values here also
        self.layer.add(animation, forKey: "shake")
    }


    // Using SpringWithDamping
    func shake(duration: TimeInterval = 0.5, xValue: CGFloat = 12, yValue: CGFloat = 0) {
        self.transform = CGAffineTransform(translationX: xValue, y: yValue)
        UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0, options: .curveEaseInOut, animations: {
            self.transform = CGAffineTransform.identity
        }, completion: nil)

    }


    // Using CABasicAnimation
    func shake(duration: TimeInterval = 0.05, shakeCount: Float = 6, xValue: CGFloat = 12, yValue: CGFloat = 0){
        let animation = CABasicAnimation(keyPath: "position")
        animation.duration = duration
        animation.repeatCount = shakeCount
        animation.autoreverses = true
        animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - xValue, y: self.center.y - yValue))
        animation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + xValue, y: self.center.y - yValue))
        self.layer.add(animation, forKey: "shake")
    }

}

按钮 Action
@IBAction func noButtonPressed(button: UIButton) {

  // for spring damping animation
  //button.shake()


  // for CAMediaTimingFunction
  button.shake(duration: 0.5, values: [-12.0, 12.0, -12.0, 12.0, -6.0, 6.0, -3.0, 3.0, 0.0])

 // for CABasicAnimation
 //button.shake(shakeCount: 10)

}

07-26 09:29