如何在swiftUI中检测摇晃手势

Lee*_*nie 10 uikit swiftui

在苹果的文档中,我没有找到任何与 swiftUI 的抖动相关的手势。那么如何检测呢?

我对 swift 编程很陌生,这个问题真的困扰了我很长时间。

在 UIKit 中,如果我想检测摇动手势非常简单直接。在 swiftUI 中,有很多手势,例如点击拖动旋转,但是我在官方文档或任何询问的人中找不到摇动手势。这有可能在 swiftUI 中达到相同的结果吗?或者他们只是忘记将它添加到 swiftUI 框架中......

如果在 swiftUI 中不可能,那么我将如何将 UIKit 中的 motionEnded 函数导入到我想要检测抖动运动的 swiftUI 视图中?

mar*_*kiv 10

您可以UIWindow.motionEnded在扩展程序中添加新通知并覆盖(如前面的答案中所述):

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个,就可以很容易地在你的视图中订阅通知:

struct Example: View {
    @State private var message = "Unshaken"

    var body: some View {
        Text(message)
            .onReceive(NotificationCenter.default.publisher(for: .deviceDidShakeNotification)) { _ in
                self.message = "Shaken, not stirred."
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 1

您可以从 ViewController 级别执行此操作。例如:

final class MyVC: UIHostingController<ContentView> {

    override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        guard motion == .motionShake else { return }

        // Notify view.
    }
}
Run Code Online (Sandbox Code Playgroud)