iOS 搖一搖功能

今天查看蘋果的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

發佈了39 篇原創文章 · 獲贊 6 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章