iOS 摇一摇事件

我知道的摇一摇有以下2种方案:

一、直接用系统自带的motionBegan方法

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

假如程序不响应此方法,试着加入下面方法:

-(BOOL)canBecomeFirstResponder

{

  return YES;

}

如果还不行,建议用第二种方法。


二、motionBegan+通知的方法

1.在Appdelegate里写motionBegan方法

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

{

[[NSNotificationCenter defaultCenter]postNotificationName:@"shake" object:self];

}

2.在需要接收通知的页面添加通知

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

写在viewDidLoad里即可。

这里的shakeAction就是摇一摇需要调用的方法,自己修改,通知名字对应就好,可自由修改。

三.补充摇一摇的其他方法

/** 摇一摇结束(需要在这里处理结束后的代码) */
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    // 不是摇一摇运动事件
    if (motion != UIEventSubtypeMotionShake) return;
    
    NSLog(@"motionEnded");
}

/** 摇一摇取消(被中断,比如突然来电) */
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    NSLog(@"motionCancelled");
}

原文地址:https://www.cnblogs.com/cai-rd/p/4428696.html