Throttling button taps in SwiftUI is essential to prevent multiple rapid actions that might lead to unintended behavior in your app. This can enhance user experience by ensuring that user inputs are managed more effectively.
In the example below, we implement a throttling mechanism using a custom view modifier that limits the frequency of button taps in SwiftUI.
struct ThrottledButton: View {
let action: () -> Void
let label: Label
@State private var lastTap: Date = .distantPast
let delay: TimeInterval
init(delay: TimeInterval, action: @escaping () -> Void, @ViewBuilder label: () -> Label) {
self.delay = delay
self.action = action
self.label = label()
}
var body: some View {
Button(action: {
let now = Date()
if now.timeIntervalSince(lastTap) > delay {
lastTap = now
action()
}
}) {
label
}
}
}
// Usage
struct ContentView: View {
var body: some View {
ThrottledButton(delay: 1.0, action: {
print("Button tapped!")
}) {
Text("Tap me")
}
}
}
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?