Created
March 1, 2022 19:04
-
-
Save ralfebert/17d4517130bec34c4b80705307e309fb to your computer and use it in GitHub Desktop.
Detect a Shake gesture in SwiftUI
This file contains hidden or 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
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