Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent repeated button presses in iOS?

Tags:

ios

swift

swift3

I'd like to stop a button from being pressed for a certain amount of time after initially being pressed successfully.
My first thought is to user a timer and disable the button for a certain amount of time but I'm unsure how to implement this.

Could someone point me in the right direction please?

I'm using swift.

like image 671
MM1010 Avatar asked Sep 29 '16 11:09

MM1010


1 Answers

No timer needed. No disabling needed.

When the button is tapped, store the current Date in an instance property. When the button is tapped again, just before you store the current Date in that same instance property, subtract the old Date from the new Date. If they are too close together, do not also perform the button's action, whatever it is.

In other words, you take action only if the two timestamps are sufficiently far apart.

This is called debouncing, and is a common technique. Do a search and you will find much discussion of it here.

like image 59
matt Avatar answered Nov 10 '22 07:11

matt