首先導入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