我在让它工作时遇到了很多问题,我最终放弃了并遵循了 jandrea 的建议。他建议继承 UIWindow 并在那里实现 motionEnded。这是他在这里的帖子的引述,请在很远的地方寻找它。
首先,我继承了 UIWindow。这很容易。使用 MotionWindow : UIWindow 等接口创建一个新的类文件(随意选择你自己的,natch)。添加这样的方法:
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"DeviceShaken" object:self];
}
}
将 @"DeviceShaken" 更改为您选择的通知名称。保存文件。
现在,如果您使用 MainWindow.xib(股票 Xcode 模板的东西),进入那里并将您的 Window 对象的类从 UIWindow 更改为 MotionWindow 或您所称的任何内容。保存xib。如果您以编程方式设置 UIWindow,请在此处使用新的 Window 类。
现在您的应用程序正在使用专门的 UIWindow 类。无论您想在哪里收到关于摇晃的消息,都可以注册他们的通知!像这样:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(deviceShaken) name:@"DeviceShaken" object:nil];
将自己作为观察者移除:
[[NSNotificationCenter defaultCenter] removeObserver:self];