Skip to content

Instantly share code, notes, and snippets.

@alexisakers
Last active October 26, 2020 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexisakers/e7333dbdd86fd3eedf967c76a306db67 to your computer and use it in GitHub Desktop.
Save alexisakers/e7333dbdd86fd3eedf967c76a306db67 to your computer and use it in GitHub Desktop.
// Author: Alexis Akers
// License:
// This code is published under the public domain. The software is provided "as is" without warranty
// of any kind and I cannot be held liable for any issue arising from its usage.
/// An object that performs haptic feedback.
struct Haptics {
/// Performs a success haptic feedback.
func success() {
let feedbackGenerator = UINotificationFeedbackGenerator()
feedbackGenerator.prepare()
feedbackGenerator.notificationOccurred(.success)
}
}
// MARK: - Environment
private enum HapticsEnvironmentKey: EnvironmentKey {
static let defaultValue = Haptics()
}
extension EnvironmentValues {
/// Returns the object responsible for performing haptic feedback in the view hierarchy.
var haptics: Haptics {
get { self[HapticsEnvironmentKey.self] }
set { self[HapticsEnvironmentKey.self} = newValue }
}
}
// MARK: - Example
struct ContentView: View {
@Environment(\.haptics) private var haptics
var body: some View {
Button(action: buttonTapped) {
Text("Tap Me!")
}
}
private func buttonTapped() {
haptics.success()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment