Skip to content

Instantly share code, notes, and snippets.

@MemoryReload
Forked from BetterProgramming/shake.swift
Created June 17, 2022 11:22
Show Gist options
  • Save MemoryReload/5d12ed8966841019c6473e428c4ac604 to your computer and use it in GitHub Desktop.
Save MemoryReload/5d12ed8966841019c6473e428c4ac604 to your computer and use it in GitHub Desktop.
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