How to prevent a UIView.animate from being called
03:45 09 Oct 2018

I'd like to reproduce the behavior of WhatsApp buttons on the ongoing call view: they disappear a few seconds after appearing, and every time the user taps the screen, they appear again.

Let's say I have those two buttons,

@IBOutlet weak var callButton: UIButton!
@IBOutlet weak var muteButton: UIButton!

This is the snippet called when viewDidAppear is entered as well as when the user taps the screen:

self.callButton.alpha = 1.0
self.muteButton.alpha = 1.0
delay(4.0) {
    UIView.animate(withDuration: 1.0, animations: {
        self.callButton.alpha = 0.0
        self.muteButton.alpha = 0.0
    }, completion: { _ in })
}

func delay(_ seconds: Double, completion: @escaping () -> ()) {
    let popTime = DispatchTime.now() + Double(Int64(Double(NSEC_PER_SEC) * seconds)) / Double(NSEC_PER_SEC)
    DispatchQueue.main.asyncAfter(deadline: popTime) {
        completion()
    }
}

With this code, if the user taps the screen like 3 seconds after the previous call, the buttons will still disappear 1 second later. So I would like to know how I can block the previous UIView.animate if the view is tapped again meanwhile.

Thanks for your help

ios swift uiview uiviewanimation