How to make buttons that repeat their action when pressed
About 2 min
How to make buttons that repeat their action when pressed 관련
SwiftUI by Example
Back to Home
How to make buttons that repeat their action when pressed | SwiftUI by Example
How to make buttons that repeat their action when pressed
Updated for Xcode 15
New in iOS 17
SwiftUI has a dedicated buttonRepeatBehavior()
modifier that trigger's a button's action repeatedly when the user holds it down. The action is triggered increasingly quickly, so it fires faster the longer the user holds it down.
For example, this adds 1 to a counter when pressed, but if you hold the button down it continues to add 1 increasingly quickly:
struct ContentView: View {
@State private var tapCount = 0
var body: some View {
Button("Tap Count: \(tapCount)") {
tapCount += 1
}
.buttonRepeatBehavior(.enabled)
}
}
This repeating behavior also works with keyboard shortcuts, although there its limited by whatever keyboard repeat rate your user has.
For example, this allows the user to hold down Shift+Return to trigger our button repeatedly:
struct ContentView: View {
@State private var tapCount = 0
var body: some View {
Button("Tap Count: \(tapCount)") {
tapCount += 1
}
.buttonRepeatBehavior(.enabled)
.keyboardShortcut(.return, modifiers: .shift)
}
}
Similar solutions…
How to show a menu when a button is pressed | SwiftUI by Example
How to show a menu when a button is pressed
How to add custom swipe action buttons to a List row | SwiftUI by Example
How to add custom swipe action buttons to a List row
How to create a toolbar and add buttons to it | SwiftUI by Example
How to create a toolbar and add buttons to it
How to let users customize toolbar buttons | SwiftUI by Example
How to let users customize toolbar buttons
How to get bordered buttons that stand out | SwiftUI by Example
How to get bordered buttons that stand out