How to add haptic effects using sensory feedback
How to add haptic effects using sensory feedback 관련
Updated for Xcode 15
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)
}
}
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)
}
}
}
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
}
}
}