如何从我的 swift 应用中处理摇动 ios 设备的支持?

How can I handle support for shaking the ios device from my swift app?

我正在编写一个 ios swift 应用程序,我想包含对摇动设备的支持。至于现在,我想在用户摇动他的 phone 时向控制台打印一条消息。我找到了这个教程 http://www.ioscreator.com/tutorials/detect-shake-gesture-ios8-swift,它看起来非常简单,但是有一件事让我很困扰。

我希望它能在应用程序的任何视图中运行,而不仅仅是一个视图。所以无论用户当前在应用程序中的哪个位置——他都应该能够调用 shake 方法。那么我应该在每个面板中实现方法 override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) { 吗?或者有没有一种方法可以实现它一次并在整个应用程序中填充它?

首先让我们找出这些 'motion' 方法的来源,正如文档所说:

UIResponder class 为响应和处理事件的对象定义了一个接口。它是UIApplication、UIView及其子class的superclass..(https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIResponder_Class/)

运动事件的事件处理方式有:

func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?)
func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?)
func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?)

因此,如您所见,为了 'catch' 应用程序每个屏幕上的运动事件 - 我们应该在这些屏幕中覆盖这些方法。感谢上帝,有了扩展——我们可以让它变得更容易 :)

为了封装 'motion' 逻辑让我们制定一个协议并将其命名为 'MotionDelegate':

protocol MotionDelegate {
func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?)
func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?)
func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?)

}

并对 UIViewController 进行扩展,符合 MotionDelegate 协议:

extension UIViewController:MotionDelegate {
override public func becomeFirstResponder() -> Bool {
    return true
}

override public func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
    if motion == .MotionShake { print("Shaking motionBegan with event\(event)") }
}

override public func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?) {
    if motion == .MotionShake { print("Shaking motionCancelled with event\(event)") }
}

override public func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
    if motion == .MotionShake { print("Shaking motionEnded with event\(event)") }
}

}

通过这种方式,运动处理将适用于您应用程序的每个 UIViewController 实例。

要处理某些 vc 上的运动事件,您应该在其扩展名中覆盖它:

extension MotionViewController {
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
    if motion == .MotionShake {
        print("MotionViewController Shaking motionEnded with event\(event)")
    }
}

}

希望对您有所帮助!