首先导入头文件
#import <AudioToolbox/AudioToolbox.h> //震动需要的库
#import <CoreMotion/CoreMotion.h> //摇一摇需要的库
//支持摇一摇并让他成为第一响应事件
[[UIApplication sharedApplication]setApplicationSupportsShakeToEdit:YES];
[self becomeFirstResponder];
具体的代码如下
@interface MotionShakeViewController ()
@property (nonatomic , strong) UILabel *pedoLab;
@end
@implementation MotionShakeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
//支持摇一摇并让他成为第一响应事件
[[UIApplication sharedApplication]setApplicationSupportsShakeToEdit:YES];
[self becomeFirstResponder];
[self.view addSubview:self.pedoLab];
}
- (UILabel *)pedoLab{
if (!_pedoLab) {
_pedoLab = [[UILabel alloc]initWithFrame:CGRectMake(20, 220, W -40, 60)];
_pedoLab.backgroundColor = DB_Blue;
_pedoLab.textColor = [UIColor whiteColor];
_pedoLab.font = Font_CN(15);
_pedoLab.textAlignment = NSTextAlignmentCenter;
}
return _pedoLab;
}
#pragma mark 摇一摇代码实现
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent*)event
{
//检测到摇动
NSLog(@"1234567开始摇动");
self.pedoLab.text = [NSString stringWithFormat:@"%@",@"开始摇动"];
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent*)event
{
//摇动取消
self.pedoLab.text = [NSString stringWithFormat:@"%@",@"摇一摇取消"];
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent*)event
{
//摇动结束
/* 系统的震动不支持ipad touch **/
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
if(event.subtype == UIEventSubtypeMotionShake) {
//somethinghappens
NSLog(@"123344554566");
self.pedoLab.text = [NSString stringWithFormat:@"%@",@"摇一摇结束"];
}
}
-(BOOL)canBecomeFirstResponder {
return YES;
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[self resignFirstResponder];
[super viewWillDisappear:animated];
}