Library / Taps & buttons

Custom keyboard key press

Each key on a custom keyboard, PIN pad, or calculator gives an instant tick on touch-down.

0ms 100ms 200ms 300ms 400ms
Feel
Very light, very crisp, zero latency. Fires on touch-down, not touch-up.
APIs
UIImpactFeedbackGenerator(style: .light)intensity 0.6
Minimum OS
iOS 13+
Raw .md
SwiftUI
import SwiftUI

struct PinPadKey: View {
    let digit: String
    let onTap: (String) -> Void

    var body: some View {
        Text(digit)
            .font(.title.monospacedDigit())
            .frame(width: 80, height: 80)
            .background(.thinMaterial, in: Circle())
            // Fire on touch-DOWN for a keyboard feel:
            .onLongPressGesture(minimumDuration: 0, perform: {}) { pressing in
                if pressing {
                    UIImpactFeedbackGenerator(style: .light)
                        .impactOccurred(intensity: 0.6)
                    onTap(digit)
                }
            }
    }
}
UIKit
final class KeyButton: UIButton {
    // One shared generator for the whole keyboard = lowest latency
    static let haptic: UIImpactFeedbackGenerator = {
        let g = UIImpactFeedbackGenerator(style: .light)
        g.prepare()
        return g
    }()

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        Self.haptic.impactOccurred(intensity: 0.6)
        Self.haptic.prepare() // re-arm for the next key
    }
}
Copied