Ios 如何使用swift加速已经发生的动画?

Ios 如何使用swift加速已经发生的动画?,ios,swift,animation,uiviewanimation,Ios,Swift,Animation,Uiviewanimation,我是UI编程新手,现在我正试图让屏幕以基于屏幕被点击次数的速度跳动。我的问题是,当检测到点击并且动画的持续时间缩短时,它会从一开始就开始动画,并在重新启动时创建白色闪光。当检测到轻触时,我将如何从动画所在的任何点开始加速动画 我的代码: class ViewController: UIViewController { var tapCount: Int = 0 var pulseSpeed: Double = 3 override func viewDidLoad()

我是UI编程新手,现在我正试图让屏幕以基于屏幕被点击次数的速度跳动。我的问题是,当检测到点击并且动画的持续时间缩短时,它会从一开始就开始动画,并在重新启动时创建白色闪光。当检测到轻触时,我将如何从动画所在的任何点开始加速动画

我的代码:

class ViewController: UIViewController {

    var tapCount: Int = 0
    var pulseSpeed: Double = 3

    override func viewDidLoad() {
        super.viewDidLoad()

        counter.center = CGPoint(x: 185, y: 118)

        pulseAnimation(pulseSpeed: pulseSpeed)
    }

    func pulseAnimation(pulseSpeed: Double) {
        UIView.animate(withDuration: pulseSpeed, delay: 0, options:   [UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse],
        animations: {
            self.red.alpha = 0.5
            self.red.alpha = 1.0
        })
    }

    @IBOutlet weak var red: UIImageView!
    @IBOutlet weak var counter: UILabel!

    @IBAction func screenTapButton(_ sender: UIButton) {
        tapCount += 1
        counter.text = "\(tapCount)"
        pulseSpeed = Double(3) / Double(tapCount)
        pulseAnimation(pulseSpeed: pulseSpeed)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

}

您需要直接使用核心动画来实现您所追求的目标,而不是依赖内置在top中的
UIView
动画

// create animation in viewDidLoad
let pulseAnimation = CABasicAnimation(keyPath: "opacity")
pulseAnimation.fromValue = 0.5
pulseAnimation.toValue = 1.0
pulseAnimation.autoreverses = true
pulseAnimation.duration = 3.0
pulseAnimation.repeatCount = .greatestFiniteMagnitude

// save animation to property on ViewController
self.pulseAnimation = pulseAnimation

// update animation speed in screenTapButton
pulseAnimation.speed += 0.5
你可能想玩一下速度数字。默认速度为1.0,动画指定的持续时间为3秒,因此从0.5到1.0再回到0.5需要6秒。当速度为2.0时,相同的动画将以两倍的速度出现,或整个循环中出现3秒

我希望这有帮助