【问题标题】:How do I stop an animation when tapped点击时如何停止动画
【发布时间】:2019-05-30 19:26:47
【问题描述】:

我正在制作一个点击游戏,这是带有动画的按钮。它非常慢,我想加快速度,所以当用户点击时,它会重置动画并计算点击次数。

目前它的速度很慢,如果在动画仍在进行时再次点击它会错过点击。

@IBAction func slimeTap(_ sender: UIButton) {
    tapCount += tapIncrease
    checkLevel(tapCount)
    UIView.animate(withDuration: 0.03, animations: {
        //shrink
        self.playSound()
        sender.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
    }, completion: {_ in
        //change it back to how it was
        //grow
        UIView.animate(withDuration: 0.05, animations: {
           sender.transform = CGAffineTransform(scaleX: 1, y: 1)
        })
    })
}

【问题讨论】:

  • 那么您是希望加快动画速度,还是在点击时停止动画?这是两种截然不同的东西。
  • 点击时停止动画。这种方式点击按钮将注册更多的点击,因为动画将结束。目前它正在处理点击时的动画而不是注册所有点击

标签: swift animation uibutton


【解决方案1】:

尝试添加.layer.removeAllAnimations() 以删除图层上的任何现有动画,并尝试添加.allowUserInteraction 作为动画选项以启用和注册用户点击事件:

@IBAction func slimeTap(_ sender: UIButton) {
    tapCount += tapIncrease
    checkLevel(tapCount)

    resizingView.layer.removeAllAnimations()

    UIView.animate(withDuration: 0.3, delay: 0, options: [.allowUserInteraction], animations: {
        self.playSound()
        sender.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
    }) { _ in
        UIView.animate(withDuration: 0.5, delay: 0, options: [.allowUserInteraction], animations: {
            sender.transform = CGAffineTransform(scaleX: 1, y: 1)
        })
    }
}

【讨论】: