curiousSloth
curiousSloth

Reputation: 79

How do I stop an animation when tapped

I'm making a tap game, and this is the button with the animation. It is very slow, and I want to speed it up so when the user taps, it will reset the animation and count the tap.

Currently, it is slow to the point that it will miss taps if tapped again while the animation is still going on.

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

Upvotes: 0

Views: 1009

Answers (1)

ZGski
ZGski

Reputation: 2548

Try adding .layer.removeAllAnimations() to remove any existing animations on the layer, and .allowUserInteraction as an animation option to enable and register user tap events:

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

Upvotes: 4

Related Questions