motionBegan:withEvent:在iOS 10中没有在AppDelegate中调用

alm*_*mas 8 uikit uiresponder ios ios10

我曾经通过简单地实现这个方法来检测来自AppDelegate的摇动:

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    NSLog(@"shake shake shake");
}
Run Code Online (Sandbox Code Playgroud)

这在iOS 8和9中运行良好.但它不再适用于iOS 10.我也尝试过添加

- (BOOL)canBecomeFirstResponder {
        return YES;
}
Run Code Online (Sandbox Code Playgroud)

但这没有帮助.这在UIViewControllers中可以正常工作.在iOS 10中有什么变化,还是只是一个bug?

小智 7

我和你有同样的问题.我现在使用UIWindow而不是在AppDelegate上实现它,它在iOS 8-10中适用于我.也许这对你来说也是可行的?

extension UIWindow {

    override open var canBecomeFirstResponder: Bool {
        return true
    }

    override open func motionBegan(_ motion: UIEventSubtype, with event: UIEvent?) {
        if motion == .motionShake {
            //logic here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想要更干净,您可以在应用程序上设置UIWindow的专用版本.


小智 -4

您应该覆盖(所有)视图控制器中的motionBegan方法。