繁体   English   中英

如何以及在何处使用 SwiftUI 实现抖动检测?

[英]How & where to implement shake detection with SwiftUI?

我正在尝试使用 SwiftUI 实现抖动检测。 到目前为止,我创建了一个符合UIViewControllerRepresentable的 ViewController 。 这样我就可以将我的 ViewController 与 SwiftUI 一起使用。 此外,我符合Coordinator器 class 中的AVAudioPlayerDelegate

在这个 VC 中,我现在想检测设备是否被晃动。 如果没有 SwiftUI 我只会实现func motionBegan(UIEvent.EventSubtype, with: UIEvent?)并基本上完成。

我现在在哪里实现这个 function? 在这一点上,我有点迷失了。 到目前为止,这是我的代码:

struct SoundViewController: UIViewControllerRepresentable {
    var audioPlayer: AVAudioPlayer?

    func makeCoordinator() -> Coordinator { // SwiftUI calls this makeCoordinator() method before makeUIViewController(context:), so that you have access to the coordinator object when configuring your view controller.
        return Coordinator(self)
    }

    func makeUIViewController(context: Context) -> UIViewController {
        return UIViewController()
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
        // TODO
    }

    class Coordinator: NSObject, AVAudioPlayerDelegate {
        var parent: SoundViewController

        init(_ soundViewController: SoundViewController) {
            self.parent = soundViewController
        }

        func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
            print("audioPlayerDidFinishPlaying Delegate")
            if flag {
                if parent.audioPlayer != nil {
                    parent.audioPlayer = nil
                }
            }
        }
    }
}

非常感谢!

我建议像这样解决您的问题:

  1. 将您的SoundViewController重命名为SoundViewSoundViewControllerRepresentable 这有两个目的:它可以防止混淆,因为这类似于 SwiftUI 的视图,而不是 UIKit 的视图 controller。 此外,我们可能希望在下一步中将该名称用于实际视图 controller。

  2. 创建客户视图 controller class (例如SoundViewController )并覆盖UIResponder.motionBegan(_:with:)UIViewController符合UIResponder 更多提示可以在SwiftUI 和 Medium 上的摇动手势中找到。

  3. 调整您的 SwiftUI 视图的makeViewController(context:)以创建SoundViewController的实例而不是UIViewController

  4. 将您想要执行的任何操作与SoundViewController ,以便在识别到的每个设备抖动时执行它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM