Skip to content

Instantly share code, notes, and snippets.

@ralfebert
Created March 1, 2022 19:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralfebert/17d4517130bec34c4b80705307e309fb to your computer and use it in GitHub Desktop.
Save ralfebert/17d4517130bec34c4b80705307e309fb to your computer and use it in GitHub Desktop.
Detect a Shake gesture in SwiftUI
import SwiftUI
/// Detect a Shake gesture in SwiftUI
/// Based on https://stackoverflow.com/a/60085784/128083
struct ShakableViewRepresentable: UIViewControllerRepresentable {
let onShake: () -> ()
class ShakeableViewController: UIViewController {
var onShake: (() -> ())?
override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake {
onShake?()
}
}
}
func makeUIViewController(context: Context) -> ShakeableViewController {
let controller = ShakeableViewController()
controller.onShake = onShake
return controller
}
func updateUIViewController(_ uiViewController: ShakeableViewController, context: Context) {}
}
extension View {
func onShake(_ block: @escaping () -> Void) -> some View {
overlay(
ShakableViewRepresentable(onShake: block).allowsHitTesting(false)
)
}
}
struct ContentView: View {
var body: some View {
Button("Example") {
print("Example")
}
.onShake {
print("Shake")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment