首先导入AudioToolbox.framework :project ->TARGETS ->General ->Linked Frameworks and Libraries
注释写的比较清晰,直接上代码了
1 #import <AudioToolbox/AudioToolbox.h>
label是从sb中随便拖过来方便摇后回调
@property (strong, nonatomic) IBOutlet UILabel *label;
- (void)viewDidLoad { [super viewDidLoad]; // 支持摇一摇 此处应该写在AppDelegate中,为粘贴代码方便写在这里 [[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES]; // 让此控制器成为第一响应者 [self becomeFirstResponder]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self resignFirstResponder]; }
重写下面方法即可摇动回调
// 开始摇动 - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { NSLog(@"开始摇动"); [self animation]; } - (void)animation { CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"]; anim.fromValue = [NSValue valueWithCGPoint:CGPointMake(100, 50)]; anim.toValue = [NSValue valueWithCGPoint:CGPointMake(100, 500)]; anim.removedOnCompletion = NO; anim.duration = 1.0f; anim.fillMode = kCAFillModeForwards; anim.delegate = self; // 随便拖过来的一个label测试效果 [self.label.layer addAnimation:anim forKey:nil]; } // 结束摇动 - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { if (event.type == UIEventSubtypeMotionShake ) { NSLog(@"摇动结束"); [self shakeshake]; } }
// 摇动结束后执行震动 - (void)shakeshake { // 震动 AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); }
完事,so easy
原文:http://www.cnblogs.com/chenshuai1012/p/4991122.html