Last active
October 26, 2020 13:55
-
-
Save alexisakers/e7333dbdd86fd3eedf967c76a306db67 to your computer and use it in GitHub Desktop.
Haptics in SwiftUI (https://alexisonline.dev/bytes/byte-2020-08-20-haptics)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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