swift 点击时如何停止动画

egdjgwm8  于 2023-01-25  发布在  Swift
关注(0)|答案(1)|浏览(166)

我正在做一个点击游戏,这是一个有动画的按钮。它非常慢,我想加快速度,这样当用户点击时,它会重置动画并计算点击次数。
目前,它的速度很慢,如果在动画仍在进行时再次点击,它将错过点击。

@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)
        })
    })
}
sg24os4d

sg24os4d1#

尝试添加.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)
        })
    }
}

相关问题