Reading time: 1 min

This recipe shows how to get haptic feedback when touching SwiftUI views.

The end result can't really be conveyed with an image, but here's what the test setup looks like:

Screenshot%202022-04-10%20at%2013.59.54

You can achieve this by triggering UIImpactFeedbackGenerator's impactOccurred method whenever your view is tapped. On top of this, you can adjust the style of the feedback with a generator parameter. Let's wrap this behavior in a ViewModifier:

struct HapticFeedback: ViewModifier {
  private let generator: UIImpactFeedbackGenerator

  init(style: UIImpactFeedbackGenerator.FeedbackStyle) {
    generator = UIImpactFeedbackGenerator(style: style)
  }

  func body(content: Content) -> some View {
    content
      .onTapGesture(perform: generator.impactOccurred)
  }
}

extension View {
  func hapticFeedback(style: UIImpactFeedbackGenerator.FeedbackStyle = .medium) -> some View {
    self.modifier(HapticFeedback(style: style))
  }
}

Then, simply attach the modifier to your views:

struct HapticFeedbackTest: View {
  var body: some View {

  VStack {
    Text("**Tap for haptic feedback! (trust me :])**")
      .hapticFeedback()

    Image("icon")
      .hapticFeedback(style: .heavy)
    }
  }
}

Next Post Previous Post