【问题标题】:Can I receive shake events in my AppDelegate?我可以在我的 AppDelegate 中接收震动事件吗?
【发布时间】:2012-10-08 15:51:15
【问题描述】:

应用程序委托是一个 UIResponder 子类(从 Xcode 4.2 开始),因此它应该能够接收触摸和运动事件。我在我的 AppDelegate 类中添加了这个,但它不起作用:

-(BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion == UIEventSubtypeMotionShake) {
        NSLog(@"shake");
    }
}

它当然可以在视图控制器中工作,但我想检测应用程序范围内的抖动。

【问题讨论】:

  • 是的,你可以,但真正的问题是......我可能错过了为什么你的 app 代表 应该参与响应任何用户交互...... .?这是一个非常奇怪的架构......
  • @holex 我希望摇动手势在应用程序的每个屏幕上都能正常工作。用法示例:在测试版中摇动以截取屏幕截图或报告反馈。

标签: iphone ios uiapplicationdelegate uiresponder


【解决方案1】:

这样做:

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [self becomeFirstResponder];

}
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {

    NSLog(@"motionBegan");

}

-(BOOL)canBecomeFirstResponder {
return YES;
}

【讨论】:

  • 我不知道为什么这被否决了。我已经尝试过这种方法并且它有效(iOS 7)......有人知道这是否会导致任何问题?
  • 对我来说也很完美!谢谢!
【解决方案2】:

我扩展了 UIApplication 类并添加了对 main 的类引用: 我的应用程序.h

@interface MyApplication : UIApplication

@end

MyApplication.m

@implementation MyApplication

- (void) sendEvent:(UIEvent *)event
{
    if( event && (event.subtype==UIEventSubtypeMotionShake))
    {
        AppDelegate *objAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

        [objAppDelegate doWhatEver];
        [super sendEvent:event];
    }
    else
    {
        [super sendEvent:event];
    }
}

@end

还有 main.m 中的最后一步

int main(int argc, char *argv[])
{
return UIApplicationMain(argc, argv, NSStringFromClass([MyApplication class]), NSStringFromClass([AppDelegate class]));
}

这适用于所有情况。

【讨论】:

    【解决方案3】:

    据我所知,它应该需要成为接收事件的第一响应者。 如果你的应用有 UINavigationController 或 UITabController,也许你可以尝试在那里接收它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      • 2011-03-06
      • 2021-07-15
      • 2018-05-15
      • 1970-01-01
      相关资源
      最近更新 更多