Updated for Xcode 16.4
New in iOS 17
SwiftUI’s sensoryFeedback() modifier provides built-in support for a range of simple haptics, which means we can create vibration effects for success, failure, selection, impacts, and more.
To trigger feedback, attach the sensoryFeedback() to any view, telling it what kind of effect to make and what the trigger should be – when the effect should be played. SwiftUI will monitor the trigger value, and run your haptic effect whenever it changes.
For example, if you had a button that marks a task as being complete, you could play a haptic when completion happens:
struct ContentView: View { @State private var taskIsComplete = false var body: some View { Button("Mark Complete") { taskIsComplete = true } .sensoryFeedback(.success, trigger: taskIsComplete) } }
Download this as an Xcode project
For more fine-grained control, you can decide exactly which type of haptic effect to trigger based on comparing the old and new value of your trigger. For example, this uses the .impact haptic effect with varying intensities based on the difference between two random numbers:
struct ContentView: View { @State private var randomNumber = 0.0 var body: some View { Button("Mark Complete") { randomNumber = Double.random(in: 0...1) } .sensoryFeedback(trigger: randomNumber) { oldValue, newValue in let amount = abs(oldValue - newValue) return .impact(flexibility: .solid, intensity: amount) } } }
Download this as an Xcode project
And finally, you can provide a fixed haptic effect and customize when it’s triggered by providing your own comparison function. As an example, this will trigger the .success haptic when the difference between two random numbers is more than 0.5:
struct ContentView: View { @State private var randomNumber = 0.0 var body: some View { Button("Mark Complete") { randomNumber = Double.random(in: 0...1) } .sensoryFeedback(.success, trigger: randomNumber) { oldValue, newValue in abs(oldValue - newValue) > 0.5 } } }
Download this as an Xcode project
SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further for less! Get my all-new book Everything but the Code to make more money with apps, get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn Swift Testing, design patterns, and more.