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

时间:2009-07-23 10:36:49

标签: iphone accelerometer shake

Apple在iPhone SDK 3.0中宣布了Shake API。我找不到有关此新功能的任何信息。

谁知道如何使用它?任何例子,链接都会很好。

3 个答案:

答案 0 :(得分: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:。

答案 1 :(得分:7)

我在这个帖子中发布了一个完整的3.0示例:

How do I detect when someone shakes an iPhone?

答案 2 :(得分:3)

Joe Hewitt最近committed使用3.0震动事件向Three20发送了一些代码。您似乎只需要在-motionBegan:withEvent:内的UIResponder内实现一些简单的代码。

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