SwiftUI.cc
Guides
GuideInteractionBeginner

How to Add Haptic Feedback in SwiftUI

Learn how to integrate haptic feedback in SwiftUI apps using the UIImpactFeedbackGenerator for enhanced user interaction.

5 min readUpdated 2026-06

Overview

Haptic feedback enhances the user experience by providing tactile sensations during interactions. In SwiftUI, you can integrate haptic feedback using UIKit's UIImpactFeedbackGenerator, which works seamlessly within SwiftUI views. This guide shows how to implement and trigger haptics effectively.

The Approach

Use UIImpactFeedbackGenerator to generate haptic responses when users interact with SwiftUI components like buttons. Here's a complete example:

import SwiftUI
import UIKit

struct HapticButton: View {
    var body: some View {
        Button(action: triggerHaptic) {
            Text("Press Me")
                .padding()
                .background(Color.blue)
                .foregroundColor(.white)
                .cornerRadius(8)
        }
    }

    func triggerHaptic() {
        let generator = UIImpactFeedbackGenerator(style: .medium)
        generator.impactOccurred()
    }
}

struct ContentView: View {
    var body: some View {
        HapticButton()
    }
}

Step-by-Step Breakdown

  1. Import UIKit: Required to access UIImpactFeedbackGenerator.
  2. Create a Button: A SwiftUI Button triggers the haptic feedback.
  3. Define triggerHaptic: Instantiates a UIImpactFeedbackGenerator with a style (e.g., .medium) and calls impactOccurred() to produce feedback.
  4. Style Options: .light, .medium, .heavy, .soft, or .rigid provide different intensity levels.
  5. Integration: The button is embedded in a ContentView for display.

Common Variations

Using a Custom Haptic Manager

To avoid repeated instantiation, create a reusable haptic manager:

class HapticManager {
    static let shared = HapticManager()
    private init() {}

    func trigger(style: UIImpactFeedbackGenerator.FeedbackStyle) {
        let generator = UIImpactFeedbackGenerator(style: style)
        generator.impactOccurred()
    }
}

// Updated Button Action
Button(action: { HapticManager.shared.trigger(style: .heavy) }) {
    Text("Heavy Impact")
        .padding()
        .background(Color.red)
        .foregroundColor(.white)
        .cornerRadius(8)
}

Using with Gesture Recognizers (SwiftUI 2.0+)

Haptics can be tied to gestures like this:

Text("Tap Me")
    .onTapGesture {
        let generator = UIImpactFeedbackGenerator(style: .light)
        generator.impactOccurred()
    }

Pitfalls to Avoid

  1. Overusing Haptics: Too many haptic triggers can overwhelm users and drain battery life.
  2. Incorrect Style Selection: Using .heavy in contexts where .light is appropriate may feel jarring.
  3. Memory Leaks in Managers: Ensure your haptic manager doesn't retain strong references unnecessarily.
  • how-to-create-custom-buttons
  • how-to-use-gestures-in-swiftui
  • how-to-add-sound-effects