SwiftUIで端末を振った時の判定(シェイク判定)を取得する方法を紹介したいと思います。
実装方法
実装方法は簡単で、extensionでNotificationCenterを使って判定し、.onReceiveでシェイク判定が取得できます。
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.onReceive(NotificationCenter.default.publisher(for: .deviceDidShakeNotification)) { _ in
print("シェイクしたよ")
}
}
}
extension NSNotification.Name {
public static let deviceDidShakeNotification = NSNotification.Name("DeviceDidShakeNotification")
}
extension UIWindow {
open override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
super.motionEnded(motion, with: event)
NotificationCenter.default.post(name: .deviceDidShakeNotification, object: event)
}
}
確認方法
実機で確認するのが一番正確ですが、シミュレーターでもcommand + control + zでシェイク判定を取得できます。

