Custom keyboard key press
Each key on a custom keyboard, PIN pad, or calculator gives an instant tick on touch-down.
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)
}
}
}
} 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
}
}