IOS开发 摇晃事件

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,
};

创建单视图应用:

  1. 新建一个UIVew(shakeView),让ViewController的根视图为新建的UIVew
  2. 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.

你可能感兴趣的:(IOS开发 摇晃事件)