【问题标题】:Programmatically trigger shake event iOS以编程方式触发 iOS 抖动事件
【发布时间】:2014-06-26 14:54:29
【问题描述】:

如何在 iOS 中以编程方式触发抖动事件?

我尝试了以下方法,但总是崩溃...

+ (void)shake {
    NSLog(@"TEST");

    UIMotionEventProxy *m = [[NSClassFromString(@"UIMotionEvent") alloc] _init];

    m->_subtype = UIEventSubtypeMotionShake;
    m->_shakeState = 1;

    [[[UIApplication sharedApplication] keyWindow] motionBegan:UIEventSubtypeMotionShake withEvent:m];
    [[[UIApplication sharedApplication] keyWindow] motionEnded:UIEventSubtypeMotionShake withEvent:m];
}

苹果在Hardware > Shake Gesture下的模拟器中做了什么?

【问题讨论】:

标签: ios triggers delegates shake


【解决方案1】:

尝试替换

UIMotionEventProxy *m = [[NSClassFromString(@"UIMotionEvent") alloc] _init];

UIMotionEventProxy *m = [[UIMotionEventProxy alloc] _init];

我猜NSClassFromString(@"UIMotionEvent") 返回 nil 时会崩溃。

【讨论】:

  • 看我的回答,这也是问题的一部分。
  • 我不明白。如果 m 是按预期创建的,那么 m->_subtype = ... 也应该可以工作。如果未创建 m,则添加 setter 将无济于事。
  • 相信跟内存使用有关,说实话还不太懂iOS。
【解决方案2】:

更改 UIMotionEventProxy 类(添加两个 setter 方法)似乎可以解决问题。我只是简单的添加了setShakeState_setSubtype这两个方法,如下图。

-(void)setShakeState:(int)fp8 {
    _shakeState = fp8;
}
-(void)_setSubtype:(int)fp8 {
    _subtype = fp8;
}

然后我将代码更改为以下...

UIMotionEventProxy *m = [[NSClassFromString(@"UIMotionEvent") alloc] _init];

[m setShakeState:1];
[m _setSubtype:UIEventSubtypeMotionShake];

[[UIApplication sharedApplication] sendEvent:m];
[[[UIApplication sharedApplication] keyWindow] motionBegan:UIEventSubtypeMotionShake withEvent:m];
[[[UIApplication sharedApplication] keyWindow] motionEnded:UIEventSubtypeMotionShake withEvent:m];

似乎在模拟器和物理设备上都能完美运行。如果有人想查看完整的 UIMotionEventProxy 文件,Here 是可供下载的主要文件和头文件。

【讨论】:

    【解决方案3】:

    您想在越狱应用中使用还是符合 Apple 标准的使用?

    对于你关于模拟器的问题,Apple 使用了一个私有函数。

    这里稍微解释一下:

    当你使用“摇动手势”时,模拟器会调用sendButtonEvent:0x3fc

    sendButtonEvent 是 Simulator 中的一个函数,他:

    • 获取最前面的AppPort
    • 通过 sendPurpleEvent 或 HIDEvent 发送消息

    在越狱应用程序中,您可以执行以下操作(未经测试,但应该可以):

    struct UIEvent {
        int subtype;
        double timestamp;
        int type;
    } * event;
    
    bzero(event, sizeof(event));
    
    event->type = UIEventTypeMotion;
    event->subtype = UIEventSubtypeMotionShake;
    event->timestamp = GSCurrentEventTimestamp();
    
    NSString* bundle = [[NSBundle mainBundle] bundleIdentifier];
    mach_port_t port = GSCopyPurpleNamedPort([bundle UTF8String]);
    
    GSEventRecord* record = (GSEventRecord*)event;
    GSSendEvent(record, port);
    

    【讨论】:

      猜你喜欢
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多