Backport of SwiftUI Sensory Feedback API (iOS 17).
// Native API. Only works on iOS 17, macOS 14, watchOS 10
.sensoryFeedback(.selection, trigger: value)
// Backport. Compatible with iOS 14, macOS 11, watchOS 7
.hapticFeedback(.selection, trigger: value)
Directly play Haptic Feedback.
// Determines if device supports haptic feedback
HapticFeedback.isAvailable
// Plays selection feedback
HapticFeedback.selection.play()
// Plays impact feedback
HapticFeedback.impact(weight: .heavy, intensity: 0.5).play()
The implementation is encapsulated in a single file, so you can simply drag the HapticFeedback.swift
file into your project to use it.
- iOS 14.0+, macCatalyst 14.0+, macOS 11.0+, watchOS 7.0+
- Swift 5.7
To use the HapticFeedback
, add the following dependency in your Package.swift
:
.package(url: "https://github.com/dm-zharov/haptic-feedback.git", from: "1.0.0")
Finally, add import HapticFeedback
to your source code.
The haptic feedback plays when the trigger values changes.
struct MyView: View {
@State private var showAccessory = false
var body: some View {
Button("Backport") {
showAccessory.toggle()
}
.hapticFeedback(.selection, trigger: showAccessory)
}
}
For more control over when you trigger the feedback use the condition closure version of the view modifier.
.hapticFeedback(.selection, trigger: showAccessory) { oldValue, newValue in
return newValue == true
}
For control over what feedback plays use the feedback closure version of the view modifier.
.hapticFeedback(trigger: isFinished) { oldValue, newValue in
return newValue ? .success : .error
}
- If you found a bug, open an issue.
- If you have a feature request, open an issue.
- If you want to contribute, submit a pull request.
Dmitriy Zharov, contact@zharov.dev
HapticFeedback is available under the MIT license. See the LICENSE file for more info.