I'm trying to implement haptic feedback at the beginning of a tap for a Button in SwiftUI. Therefore I'm trying to use simultaneousGesture, but I'm sill struggling. I can't manage to figure out when the tap begins.
Also there is no Haptic feedback implemented for Swift UI, so I guess I would blend it in from UIKit?
I tried to implement the updating method of the TapGesture but it does not seem to do anything. This is what I've got so far. Thanks for any hints.
struct HapticButton : View { @GestureState var isDetectingTap = false var body: some View { let tap = TapGesture() .updating($isDetectingTap) { (body, stateType, transaction) in // nothing happens below print(body) print(stateType) print(transaction) }.onEnded { _ in // this one works but it is to late // I need to figure out the beginning of the tap print("Button was tapped, will invoke haptic feedback, maybe with UIKit") } return Button(action: { print("Action executed") }) { HStack { Image("icon") Text("Login") } }.simultaneousGesture(tap) } }
Haptics uses a vibrating component (sometimes called an actuator) such as a vibration motor or a linear resonant actuator which is driven by an electronic circuit. It is common for a microcontroller to decide when to vibrate and with which pattern, and for a dedicated haptic driver chip to control the actuator.
Several Android smartphones come with haptic feedback enabled by default, it means the keyboard on your smartphone will vibrate a little bit on a keypress giving you a type of feedback of a physical key pressed.
Haptic feedback (often shortened to just haptics) changes this by simulating the sense of touch. Not only can you touch a computer or other device, but the computer can touch you back. Haptic feedback (sometimes described as "force feedback") first entered game controllers in the late 1990s and is ubiquitous today.
As I know, this is the most simplest way to get haptic feedback in SwiftUI
When tapping a button :
Button(action: { let impactMed = UIImpactFeedbackGenerator(style: .medium) impactMed.impactOccurred() }) { Text("This is a Button") }
You can change the intensity of the haptic feedback by replacing .medium
with .soft
, .light
, .heavy
, or .rigid
or when tapping anything else :
.onTapGesture { let impactHeavy = UIImpactFeedbackGenerator(style: .heavy) impactHeavy.impactOccurred() }
If you want to make something like Haptic Touch, replace .onTapGesture
with .onLongPressGesture
like this
.onLongPressGesture { let impactHeavy = UIImpactFeedbackGenerator(style: .heavy) impactHeavy.impactOccurred() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With