今天查看蘋果的API文檔,突然發現搖一搖功能iOS有自帶,灰常欣喜,記錄一下。
在UIResponder中存在着這麼一套方法:
//檢測到搖動
- (void)motionBegan:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event NS_AVAILABLE_IOS(3_0);
//搖動結束
- (void)motionEnded:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event NS_AVAILABLE_IOS(3_0);
//搖動取消
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(nullable UIEvent *)event NS_AVAILABLE_IOS(3_0);
具體實現就是:
1.讓viewcontroller支持搖動;
2.讓viewcontroller成爲第一響應者;
3.實現上面這幾個方法。
代碼如下:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//讓viewcontroller支持搖動
[[UIApplication sharedApplication] setApplicationSupportsShakeToEdit:YES];
//讓viewcontroller成爲第一響應者
[self becomeFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
#pragma mark -
#pragma mark --支持搖動--
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"搖動開始");
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
// 添加手機響鈴的方法
SystemSoundID soundId;
NSString *path = [[NSBundle mainBundle]pathForResource:@"song" ofType:@"wav"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundId);
AudioServicesPlaySystemSound(soundId);
}
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
NSLog(@"搖動取消");
}
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (event.subtype == UIEventSubtypeMotionShake) {
NSLog(@"搖動結束");
}
}
Demo地址:https://github.com/KityPei/MotionDemo.git