首先让我们找出这些“运动”方法的来源,正如文档所说:
UIResponder 类为响应和处理事件的对象定义了一个接口。它是 UIApplication、UIView 及其子类的超类。(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?)
因此,如您所见,要在应用程序的每个屏幕上“捕捉”运动事件 - 我们应该在这些屏幕中覆盖这些方法。感谢上帝,有了扩展 - 我们可以让它变得更容易:)
为了包含“运动”逻辑,让我们创建一个协议并将其命名为“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)")
}
}
}
希望能帮助到你!