如何检测有人摇晃 iPhone? [英] How do I detect when someone shakes an iPhone?

查看:16
本文介绍了如何检测有人摇晃 iPhone?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在有人摇晃 iPhone 时做出反应.我并不特别关心他们是如何摇晃它的,只是它被猛烈地挥动了一瞬间.有人知道如何检测吗?

I want to react when somebody shakes the iPhone. I don't particularly care how they shake it, just that it was waved vigorously about for a split second. Does anyone know how to detect this?

推荐答案

在 3.0 中,现在有一个更简单的方法 - 连接到新的动作事件.

In 3.0, there's now an easier way - hook into the new motion events.

主要技巧是您需要有一些 UIView(而不是 UIViewController)作为 firstResponder 来接收震动事件消息.这是您可以在任何 UIView 中使用以获取抖动事件的代码:

The main trick is that you need to have some UIView (not UIViewController) that you want as firstResponder to receive the shake event messages. Here's the code that you can use in any UIView to get shake events:

@implementation ShakingView

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if ( event.subtype == UIEventSubtypeMotionShake )
    {
        // Put in code here to handle shake
    }

    if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
        [super motionEnded:motion withEvent:event];
}

- (BOOL)canBecomeFirstResponder
{ return YES; }

@end

您可以轻松地将任何 UIView(甚至系统视图)转换为可以通过仅使用这些方法对视图进行子类化(然后在 IB 中选择此新类型而不是基类型,或使用它)来获取抖动事件的视图分配视图时).

You can easily transform any UIView (even system views) into a view that can get the shake event simply by subclassing the view with only these methods (and then selecting this new type instead of the base type in IB, or using it when allocating a view).

在视图控制器中,您希望将此视图设置为第一响应者:

In the view controller, you want to set this view to become first responder:

- (void) viewWillAppear:(BOOL)animated
{
    [shakeView becomeFirstResponder];
    [super viewWillAppear:animated];
}
- (void) viewWillDisappear:(BOOL)animated
{
    [shakeView resignFirstResponder];
    [super viewWillDisappear:animated];
}

不要忘记,如果您有其他视图通过用户操作(例如搜索栏或文本输入字段)成为第一响应者,您还需要在其他视图退出时恢复震动视图第一响应者状态!

Don't forget that if you have other views that become first responder from user actions (like a search bar or text entry field) you'll also need to restore the shaking view first responder status when the other view resigns!

即使您将 applicationSupportsShakeToEdit 设置为 NO,此方法也有效.

This method works even if you set applicationSupportsShakeToEdit to NO.

这篇关于如何检测有人摇晃 iPhone?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆