Haptic feedback provides a tactile response, such as a tap, which draws attention and reinforces both actions and events. In iOS, many components such as pickers, switch and sliders automatically provide haptic feedback but we can use feedback generators to add our own feedback for custom views or controls.
In this article we will explore UIImpactFeedbackGenerator. UIImpactFeedbackGenerator is a concrete feedback generator subclass of UIFeedbackGenerator which creates haptics to simulate physical impacts. We use impact feedback to indicate that an impact has occurred.
We will create a customer ViewModifier which will wrap behavior for impact generator.
struct HapticFeedback: ViewModifier {
private let generator: UIImpactFeedbackGenerator
init(feedbackStyle: UIImpactFeedbackGenerator.FeedbackStyle) {
generator = UIImpactFeedbackGenerator(style: feedbackStyle)
}
func body(content: Content) -> some View {
content
.onTapGesture {
generator.impactOccurred()
}
}
}
We will create a View extension to create function for haptic feedback.
extension View {
func hapticFeedback(feedbackStyle: UIImpactFeedbackGenerator.FeedbackStyle = .heavy) -> some View {
self.modifier(HapticFeedback(feedbackStyle: feedbackStyle))
}
}
With this custom modifier in place, its easy for us to place haptic feedback in view.
struct DevTechieImpactGeneratorExample: View {
var body: some View {
VStack(spacing: 20) {
Text("DevTechie")
.font(.largeTitle)
.hapticFeedback(feedbackStyle: .medium)
Button("Tap me for feedback") {
print("Tapped")
}
.hapticFeedback()
}
}
}
Running this in simulator will now show us the effect so build and run on device to test the feedback.
With that we have reached the end of this article. Thank you once again for reading. Don’t forget to subscribe our newsletter at https://www.devtechie.com