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
- Import UIKit: Required to access
UIImpactFeedbackGenerator. - Create a Button: A SwiftUI
Buttontriggers the haptic feedback. - Define
triggerHaptic: Instantiates aUIImpactFeedbackGeneratorwith a style (e.g.,.medium) and callsimpactOccurred()to produce feedback. - Style Options:
.light,.medium,.heavy,.soft, or.rigidprovide different intensity levels. - Integration: The button is embedded in a
ContentViewfor 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
- Overusing Haptics: Too many haptic triggers can overwhelm users and drain battery life.
- Incorrect Style Selection: Using
.heavyin contexts where.lightis appropriate may feel jarring. - Memory Leaks in Managers: Ensure your haptic manager doesn't retain strong references unnecessarily.
Related Guides
- how-to-create-custom-buttons
- how-to-use-gestures-in-swiftui
- how-to-add-sound-effects