# Haptics in SwiftUI

In today’s post, we’re going to learn how to implement haptics (vibration) on an iOS or iPadOS device.

The source code of this demo is available [here](https://github.com/xavier7t/DemoHatic20230218).

**Note: You need a physical device to actually check the haptic effects. If you don’t have one, you can add some print statements and check them in the debug console while you toggle the haptics in the simulator.**

# Overview and some terms to know

What we’ll be building today is a simple view with a button, which can toggle different types of haptic effects on an iPhone.

A haptic effect can be described from two dimensions:

* Strength - how strong one vibration is generated by one toggle.
    
* Frequency - how many times of vibration is generated by one toggle.
    

To toggle the haptics we need `UINotificationFeedbackGenerator`, which is a class available after iOS 10. This class contains a function called `impact`, to which we can assign a strength value (such as heavy, soft, light etc.). Another function called `notification` represents the frequency and the default values are `.success`, `.warning` and `.error`.

# Add a button to toggle default haptics

Now create a new project, and in the content view, declare a button with the label "Tap me". In the action of the button, declare an instance of `UINotificationFeedbackGenerator` without an init. Then we can call its function `notificationOccurred` with a value of `FeedbackType` (such as `.success`, `.warning` and `.error`) passed in. Now you should be able to feel the vibration on tap gesture of this button.

```swift
struct ContentView: View {
    var body: some View {
        VStack {
            Button("Tap me") {
                let generator = UINotificationFeedbackGenerator()
                generator.notificationOccurred(.error)
            }
        }
        .padding()
    }
}
```

# Change the strength of the haptic

Now, let’s comment (or remove) the action of the button. This time, we’ll need to initialize a generator with an impact style of the type `FeedbackStyle`.

The values you can pass in include `.light`, `.medium`, `.heavy`, `.soft` and `.rigid`.

And call the function `impactOccurred()` to trigger the haptic with the impact configured.

```swift
struct ContentView: View {
    var body: some View {
        VStack {
            Button("Tap me") {
//                let generator = UINotificationFeedbackGenerator()
//                generator.notificationOccurred(.error)
                let generator = UIImpactFeedbackGenerator(style: .heavy)
                generator.impactOccurred()
            }
        }
        .padding()
    }
}
```

Now when you change the style value, you can feel the strength are changed accordingly.

That’s all of today’s tip-sharing post. Hope it helps and see you all tomorrow!

Remember to leave a comment and subscribe to my newsletter!
