Haptic feedback (Vibration) in SwiftUI using sensoryFeedback

In this tutorial, I will show you how to add haptic feedback on button press in SwiftUI.

The modifier we need is: .sensoryFeedback(parameters)
Before iOS 17, we were required to use UIkit to deal with haptic feedback.

Thanks to Apple they make it easier for us to deal with the vibration effect (haptic feedback) from iOS 17.

You can check: is only available in iOS 17.0 or newer – Working solution if you are getting error like sensoryFeedback(_:trigger:)' is only available in iOS 17.0 or newer.

Haptic feedback happens triggered when the value changes.

Haptic feedback on value changes in SwiftUI (Button press)

It’s better to see an example first before diving in.

import SwiftUI

struct ContentView: View {
    @State private var counter = 0
    
    var body: some View {
        Button("I am pressed!\(counter)"){
            counter = counter + 1
        }
        .sensoryFeedback(.increase, trigger: counter)
    }
}

Output:

When you run this on an actual physical device (make sure it is iOS 17 or newer version), you will see the button. On clicking on that button, it will give you a slight vibration effect which is known as haptic feedback.

Haptic Feedback in SwiftUI

In the first parameter of .sensoryFeeback, you can see there are a lot of options.

Each option produces different types of feedback. Check those one by one yourself to get an idea of what type of feedback they produce.

In the second parameter, we are using trigger: . This is the parameter where we declare on whose value changes the feedback should come out.

In the above example, I set counter in the second parameter. That means whenever the value of counter will change, it will produce feedback.

.sensoryFeedback(.success, trigger: counter)

This will produce stronger haptic feedback.

.sensoryFeedback(.stop, trigger: counter)– This will produce no haptic feedback for the iPhone.

.start and .stop are only for watchOS only.

Increase the intensity of Haptic feedback

You can do this:

.sensoryFeedback(.impact(flexibility: .rigid, intensity: 1.0), trigger: counter)

.impact will give you a lot more control over the haptic feedback.

Changing the sensoryFeedback weight

If you wish you can get control over the feedback like this:

.sensoryFeedback(.impact(weight: .light, intensity: 1), trigger: counter)

The weight can be light, medium or heavy.

Light is more likely the collision between to light UI elements.

Also learn Haptic Feedback with Sound in SwiftUI – sensoryFeedback

Conclusion:

There are a lot more options that you can check out from the official documentation: sensoryFeedback

Leave a Reply

Your email address will not be published. Required fields are marked *