In UIKit with Swift, it's often necessary to throttle button taps to prevent multiple rapid executions of a task. Throttling allows you to limit the number of times a function can be invoked over a specific period. Here’s how you can implement throttling for button taps in a simple Swift app.
import UIKit
class ViewController: UIViewController {
var lastTapTime: Date?
@IBOutlet weak var myButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
myButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
}
@objc func buttonTapped() {
let currentTime = Date()
if lastTapTime == nil || currentTime.timeIntervalSince(lastTapTime!) > 1.0 {
lastTapTime = currentTime
performAction()
} else {
print("Button tap ignored")
}
}
func performAction() {
print("Button tapped and action performed")
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?