How to make haptics in SwiftUI

Asked on 07/31/2024

1 search

To make haptics in SwiftUI, you can use the new feedback APIs introduced for alignment, snapping, and completing a path. These APIs are available in both SwiftUI and UIKit. Here is a brief overview of how you can implement haptics in SwiftUI:

  1. Use Sensory Feedback Modifiers: SwiftUI offers sensory feedback modifiers that you can add to your views. These modifiers will request feedback whenever the trigger value changes.

  2. Example Implementation:

    • Define state variables that will trigger the feedback.
    • Use sensory feedback modifiers on the specific views where you want the feedback to occur.

Here is a code snippet to illustrate this:

import SwiftUI

struct ContentView: View {
    @State private var alignmentTrigger: Int = 0
    @State private var pathCompleteTrigger: Int = 0

    var body: some View {
        VStack {
            // Your custom canvas or view
            CanvasView()
                .onAlignmentChange {
                    alignmentTrigger += 1
                }
                .onPathComplete {
                    pathCompleteTrigger += 1
                }
                .sensoryFeedback(.alignment, trigger: $alignmentTrigger)
                .sensoryFeedback(.pathComplete, trigger: $pathCompleteTrigger)
        }
    }
}

In this example:

  • CanvasView is your custom view where you want to provide haptic feedback.
  • onAlignmentChange and onPathComplete are custom methods that increment the state variables.
  • sensoryFeedback modifiers are used to provide haptic feedback when the state variables change.

For more details, you can refer to the session Squeeze the most out of Apple Pencil at WWDC 2024.

Relevant Sessions