如何在iPhone SDK 3.0中使用Shake API?

15

苹果在iPhone SDK 3.0中宣布了Shake API,但我找不到有关这个新功能的任何信息。

谁知道如何使用它?有任何示例或链接都可以。

3个回答

36

你需要查找的API在UIResponder中:

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event;
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;

通常你只需要实现这个:

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
  if (event.type == UIEventSubtypeMotionShake) {
    //Your code here
  }
}

在你的UIViewController子类中(UIViewController是UIResponder的一个子类)。此外,你想在motionEnded:withEvent:中处理它,而不是在motionBegan:withEvent:中处理。当手机检测到晃动时调用motionBegan:withEvent:,但操作系统可以区分用户有意图地摇动和意外的震动(如上楼梯)之间的差异。如果操作系统在调用motionBegan:withEvent:后确定这不是真正的晃动,则会调用motionCancelled:而不是motionEnded:withEvent:。


如果我说我们需要在需要摇晃手势工作的视图上添加代码 [self becomeFirstResponder];,那么我是正确的吗? - Parth Bhatt
1
你说得对。另外:(BOOL)canBecomeFirstResponder {return YES;} - akaru

7

继续阅读,我的回复确实使用了3.0版本。我使用了上面发布的事件,只是我还解释了需要将UIView设置为第一响应者的重要性,这对其实际工作非常关键。 - Kendall Helmstetter Gelner

3

Joe Hewitt最近提交了一些代码到Three20中,利用了3.0的摇晃事件。看起来你只需要在UIResponder内部实现一些简单的代码,在-motionBegan:withEvent:中。

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (event.type == UIEventSubtypeMotionShake) {
        ...
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接