Created
May 25, 2022 04:35
-
-
Save BetterProgramming/d0bf762bbecc80a0427c6935a48c470d to your computer and use it in GitHub Desktop.
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
extension NSNotification.Name { | |
public static let deviceDidShakeNotification = NSNotification.Name("MyDeviceDidShakeNotification") | |
} | |
extension UIWindow { | |
open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) { | |
super.motionEnded(motion, with: event) | |
NotificationCenter.default.post(name: .deviceDidShakeNotification, object: event) | |
} | |
} | |
extension View { | |
func onShake(perform action: @escaping () -> Void) -> some View { | |
self.modifier(ShakeDetector(onShake: action)) | |
} | |
} | |
struct ShakeDetector: ViewModifier { | |
let onShake: () -> Void | |
func body(content: Content) -> some View { | |
content | |
.onAppear() // this has to be here because of a SwiftUI bug | |
.onReceive(NotificationCenter.default.publisher(for: | |
.deviceDidShakeNotification)) { _ in | |
onShake() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment