Adding haptics and button sounds
Haptics are a form of sensory feedback that works by accessing the internal vibration hardware on an iPhone, providing a physical response when the phone is being used. You are probably familiar with haptics, as it’s felt every time we set our phones to vibrate. We won’t use a full vibration but just a brief one that the user can feel every time they click on a button.
The best place to add such code is in the button itself, so let’s do that. We’re going to use the UIImpactFeedbackGenerator
class for this, and it is actually quite simple to implement. First, inside ContentView
, we need an instance of that class underneath all the properties that we already added:
//haptic feedback var hapticImpact = UIImpactFeedbackGenerator(style: .medium)
We have set the hapticImpact
variable style to medium
, but you can set the vibration to heavy
, light
, ridged
, or soft
.
Now, to use this, we just simply call this...