Skip to content

Instantly share code, notes, and snippets.

@thejohnlima
Last active March 11, 2022 13:27
Show Gist options
  • Save thejohnlima/f859d3539c82432c65500f6ece82c827 to your computer and use it in GitHub Desktop.
Save thejohnlima/f859d3539c82432c65500f6ece82c827 to your computer and use it in GitHub Desktop.
Implements haptic feedback as a View extension in SwiftUI

The hapticFeedback function can be used like in the following view file, just calling it in the button action and the haptic feedback will be fired when the button is tapped.

close_button_view

import SwiftUI
extension View {
/// Haptic Feedback
/// - Parameters:
/// - style: Feedback Style
/// - type: Feedback Type
func hapticFeedback(_ style: UIImpactFeedbackGenerator.FeedbackStyle? = nil,
type: UINotificationFeedbackGenerator.FeedbackType? = nil) {
if let style = style {
let feedback = UIImpactFeedbackGenerator(style: style)
feedback.impactOccurred()
} else if let type = type {
let feedback = UINotificationFeedbackGenerator()
feedback.notificationOccurred(type)
} else {
UIImpactFeedbackGenerator().impactOccurred()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment