iOS開發之搖晃事件
iso開發實現搖晃事件
搖晃事件相對簡單,視圖出現時成為第一響應者,視圖移除時取消第一響應者,當稱為第一響應者時,添加搖晃事件監聽。
搖晃事件監聽的方法:
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);
//UIEventSubtype 對應的枚舉的值,
//UIEventSubtypeMotionShake= 1,此枚舉值即為搖晃事件。
typedef NS_ENUM(NSInteger, UIEventSubtype) {
// available in iPhone OS 3.0
UIEventSubtypeNone = 0,
// for UIEventTypeMotion, available in iPhone OS 3.0
UIEventSubtypeMotionShake = 1,
// for UIEventTypeRemoteControl, available in iOS 4.0
UIEventSubtypeRemoteControlPlay = 100,
UIEventSubtypeRemoteControlPause = 101,
UIEventSubtypeRemoteControlStop = 102,
UIEventSubtypeRemoteControlTogglePlayPause = 103,
UIEventSubtypeRemoteControlNextTrack = 104,
UIEventSubtypeRemoteControlPreviousTrack = 105,
UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
UIEventSubtypeRemoteControlEndSeekingBackward = 107,
UIEventSubtypeRemoteControlBeginSeekingForward = 108,
UIEventSubtypeRemoteControlEndSeekingForward = 109,
};
創建單視圖應用:
新建一個UIVew(shakeView),讓ViewController的根視圖為新建的UIVew
shakeView添加: canBecomeFirstResponder方法,使其成為第一響應者。
詳細實現代碼:
/*
1.在視圖出現在屏幕時,讓視圖變成第一響應者
2.當視圖離開屏幕時,應用關閉或者切換到其他視圖時,注銷第一響應者身份
3.監聽搖晃事件
*/
- (void)viewDidAppear:(BOOL)animated
{
[self.view becomeFirstResponder];
}
- (void)viewDidDisappear:(BOOL)animated
{
[self.view resignFirstResponder];
}
#pragma mark - 監聽運動事件
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
if (UIEventSubtypeMotionShake ==motion) {
NSLog(@"The view is shake.");
}
}
在模擬器中 搖晃是在:Handware->shake Gesture.