代码之家  ›  专栏  ›  技术社区  ›  Josh Gagnon Steinar

当有人摇晃iPhone时,我如何检测?

  •  337
  • Josh Gagnon Steinar  · 技术社区  · 18 年前

    16 回复  |  直到 11 年前
        1
  •  293
  •   logancautrell    15 年前

    在3.0中,现在有了一种更简单的方法——加入新的动作事件。

    @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中选择此新类型而不是基本类型,或者在分配视图时使用它),即可获得抖动事件。

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

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

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

        2
  •  180
  •   millenomi    18 年前

    从我的 Diceshaker 应用程序:

    // Ensures the shake is strong enough on at least two axes before declaring it a shake.
    // "Strong enough" means "greater than a client-supplied threshold" in G's.
    static BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {
        double
            deltaX = fabs(last.x - current.x),
            deltaY = fabs(last.y - current.y),
            deltaZ = fabs(last.z - current.z);
    
        return
            (deltaX > threshold && deltaY > threshold) ||
            (deltaX > threshold && deltaZ > threshold) ||
            (deltaY > threshold && deltaZ > threshold);
    }
    
    @interface L0AppDelegate : NSObject <UIApplicationDelegate> {
        BOOL histeresisExcited;
        UIAcceleration* lastAcceleration;
    }
    
    @property(retain) UIAcceleration* lastAcceleration;
    
    @end
    
    @implementation L0AppDelegate
    
    - (void)applicationDidFinishLaunching:(UIApplication *)application {
        [UIAccelerometer sharedAccelerometer].delegate = self;
    }
    
    - (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    
        if (self.lastAcceleration) {
            if (!histeresisExcited && L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.7)) {
                histeresisExcited = YES;
    
                /* SHAKE DETECTED. DO HERE WHAT YOU WANT. */
    
            } else if (histeresisExcited && !L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.2)) {
                histeresisExcited = NO;
            }
        }
    
        self.lastAcceleration = acceleration;
    }
    
    // and proper @synthesize and -dealloc boilerplate code
    
    @end
    

    histeresis可防止多次触发抖动事件,直到用户停止抖动。

        3
  •  154
  •   logancautrell    15 年前

    最后,我使用本文中的代码示例实现了它 Undo/Redo Manager Tutorial
    这正是您需要做的:

  • 设定 应用程序的委托中的属性:
  • 
        - (void)applicationDidFinishLaunching:(UIApplication *)application {
    
            application.applicationSupportsShakeToEdit = YES;
    
            [window addSubview:viewController.view];
            [window makeKeyAndVisible];
    }
    

  • 添加/覆盖 可以成为第一反应者 , 和 视图将消失: 视图控制器中的方法:
  • 
    -(BOOL)canBecomeFirstResponder {
        return YES;
    }
    
    -(void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        [self becomeFirstResponder];
    }
    
    - (void)viewWillDisappear:(BOOL)animated {
        [self resignFirstResponder];
        [super viewWillDisappear:animated];
    }
    

  • 运动结束
  • 
    - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
    {
        if (motion == UIEventSubtypeMotionShake)
        {
            // your code
        }
    }
    
        4
  •  94
  •   Joe D'Andrea    17 年前

    首先,肯德尔7月10日的回答很准确。

    现在我想做一些类似的事情(在iPhoneOS3.0+中),只是在我的情况下,我想让它应用范围更广,这样我就可以发出警报

    首先,我将其子类化 UIWindow . 这很容易。使用以下接口创建一个新类文件: MotionWindow : UIWindow (natch,你可以自由选择)。添加如下方法:

    - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
        if (event.type == UIEventTypeMotion && event.subtype == UIEventSubtypeMotionShake) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"DeviceShaken" object:self];
        }
    }
    

    @"DeviceShaken" 到您选择的通知名称。保存文件。

    现在,如果您使用MainWindow.xib(StockXcode模板),请进入其中并将窗口对象的类从 UIWindow 到 UIWindow 以编程方式,在那里使用新的窗口类。

    UIWindow 班无论你想在哪里听到关于奶昔的消息,都可以注册他们的通知!这样地:

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(deviceShaken) name:@"DeviceShaken" object:nil];
    

    要取消自己作为观察者的身份,请执行以下操作:

    [[NSNotificationCenter defaultCenter] removeObserver:self];
    

    视图将显示: 和 涉及视图控制器的位置。确保您对震动事件的响应知道是否“正在进行”。否则,如果设备连续摇晃两次,就会出现交通堵塞。这样,您可以忽略其他通知,直到您真正完成对原始通知的响应。

    另外:你也可以选择暗示 运动开始了 运动结束 . 这取决于你。在我的例子中,效果总是需要发生的 之后 设备处于静止状态(而不是开始摇晃),因此我使用 . 两个都试试看哪一个更有意义。。。或检测/通知两者!

    这里还有一个(奇怪的?)观察:注意在这段代码中没有第一响应者管理的迹象。到目前为止,我只在表视图控制器上尝试过这个方法,所有的东西似乎都能很好地协同工作!但我不能保证其他情况。

    肯德尔等人——有人能解释为什么这对我们来说是如此吗 子类?是因为窗户在食物链的顶端吗?

        5
  •  35
  •   Jeremy Ellison Jeremy Ellison    18 年前

    我在这篇文章中找到了一个“震撼”的实现。millenomi的回答对我来说很有效,尽管我在寻找需要更多“震动动作”才能触发的东西。我用int shakeCount替换为布尔值。我还重新实现了Objective-C中的l0AccelerationsShacking()方法。通过调整添加到shakeCount中的数量,可以调整所需的震动数量。我不确定我是否找到了最佳值,但到目前为止它似乎运行良好。希望这对某人有所帮助:

    - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
        if (self.lastAcceleration) {
            if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7] && shakeCount >= 9) {
                //Shaking here, DO stuff.
                shakeCount = 0;
            } else if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7]) {
                shakeCount = shakeCount + 5;
            }else if (![self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.2]) {
                if (shakeCount > 0) {
                    shakeCount--;
                }
            }
        }
        self.lastAcceleration = acceleration;
    }
    
    - (BOOL) AccelerationIsShakingLast:(UIAcceleration *)last current:(UIAcceleration *)current threshold:(double)threshold {
        double
        deltaX = fabs(last.x - current.x),
        deltaY = fabs(last.y - current.y),
        deltaZ = fabs(last.z - current.z);
    
        return
        (deltaX > threshold && deltaY > threshold) ||
        (deltaX > threshold && deltaZ > threshold) ||
        (deltaY > threshold && deltaZ > threshold);
    }
    

    附言: 我已将更新间隔设置为1/15秒。

    [[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 15)];
    
        6
  •  13
  •   nhgrif    11 年前

    在iOS 8.3(可能更早)中,使用Swift,只需覆盖 motionBegan 或 motionEnded 视图控制器中的方法:

    class ViewController: UIViewController {
        override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {
            println("started shaking!")
        }
    
        override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
            println("ended shaking!")
        }
    }
    
        7
  •  12
  •   sabiland    18 年前

    您需要通过Accelerator:didAccelerate:method(UIAccelerometerDelegate协议的一部分)检查加速计,并检查值是否超过抖动所需移动量的阈值。

    iPhone开发者网站上提供的GLPaint示例中AppController.m底部的Accelerator:didAccelerate:method中有不错的示例代码。

        8
  •  10
  •   me1974 Benjamin Ortuzar    15 年前

    这是您需要的基本代理代码:

    #define kAccelerationThreshold      2.2
    
    #pragma mark -
    #pragma mark UIAccelerometerDelegate Methods
        - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration 
        {   
            if (fabsf(acceleration.x) > kAccelerationThreshold || fabsf(acceleration.y) > kAccelerationThreshold || fabsf(acceleration.z) > kAccelerationThreshold) 
                [self myShakeMethodGoesHere];   
        }
    

    还可以在界面中的相应代码中设置。即:

    @接口MyViewController:UIViewController<UIPickerViewDelegate、UIPickerViewDataSource、UIAccelerometerDelegate>

        10
  •  7
  •   Himanshu Mahajan    14 年前

        -(BOOL) canBecomeFirstResponder
        {
             /* Here, We want our view (not viewcontroller) as first responder 
             to receive shake event message  */
    
             return YES;
        }
    
        -(void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
        {
                if(event.subtype==UIEventSubtypeMotionShake)
                {
                        // Code at shake event
    
                        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Motion" message:@"Phone Vibrate"delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
                        [alert show];
                        [alert release];
    
                        [self.view setBackgroundColor:[UIColor redColor]];
                 }
        }
        - (void)viewDidAppear:(BOOL)animated
        {
                 [super viewDidAppear:animated];
                 [self becomeFirstResponder];  // View as first responder 
         }
    
        11
  •  5
  •   logancautrell    15 年前

    很抱歉将此作为回答而不是评论发布,但正如您所看到的,我对Stack Overflow是新手,因此我的声誉还不足以发布评论!

    无论如何,我建议@cire确保在视图成为视图层次结构的一部分后设置第一响应者状态。因此,在视图控制器中设置第一响应者状态 viewDidLoad 例如,方法不起作用。如果你不确定它是否有效 [view becomeFirstResponder]

    另一点:你 可以 如果不想不必要地创建UIView子类,请使用视图控制器捕获抖动事件。我知道这没什么麻烦,但还是有选择的余地。只需将Kendall放入UIView子类的代码片段移动到控制器中,并发送 becomeFirstResponder 和 resignFirstResponder self 而不是UIView子类。

        12
  •  5
  •   Dennis gnasher729    11 年前

    首先,我知道这是一个老帖子,但它仍然是相关的,我发现投票率最高的两个答案没有 尽早检测震动 . 这是如何做到的:

    1. 将CoreMotion链接到目标构建阶段的项目: CoreMotion
    2. 在ViewController中:

      - (BOOL)canBecomeFirstResponder {
          return YES;
      }
      
      - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
      {
          if (motion == UIEventSubtypeMotionShake) {
              // Shake detected.
          }
      }
      
        13
  •  4
  •   mxcl    12 年前

    @implementation OMGWindow : UIWindow
    
    - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
        if (event.type == UIEventTypeMotion && motion == UIEventSubtypeMotionShake) {
            // via notification or something   
        }
    }
    @end
    

    然后在您的应用程序委托中:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        self.window = [[OMGWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        //…
    }
    

    如果您使用的是故事板,这可能会更棘手,我不知道您在应用程序委托中需要什么代码。

        14
  •  1
  •   Mashhadi    13 年前

    只需使用这三种方法即可

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

    有关详细信息,请查看完整的示例代码 there

        15
  •  1
  •   user3069232    9 年前

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
        if ( event?.subtype == .motionShake )
        {
            print("stop shaking me!")
        }
    }
    
        16
  •  0
  •   Amit Baderia    5 年前

    在swift 5中,这是您捕捉运动并检查的方式

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
       if motion == .motionShake 
       {
          print("shaking")
       }
    }
    
        17
  •  -1
  •   Mike    9 年前

    要在整个应用程序范围内启用此应用程序,我在UIWindow上创建了一个类别:

    @implementation UIWindow (Utils)
    
    - (BOOL)canBecomeFirstResponder
    {
        return YES;
    }
    
    - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
    {
        if (motion == UIEventSubtypeMotionShake) {
            // Do whatever you want here...
        }
    }
    
    @end