您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 搖晃手勢(Shake)實作教學

編輯:iOS 相關資訊

搖晃偵測在 iOS 上比想像中簡單,核心觀念只有一個:讓你的視圖成為第一響應者(first responder)。

整體邏輯是三個時機點——視圖出現時成為第一響應者,視圖離開時取消這個身份,成為第一響應者之後就能收到搖晃事件。

相關 API

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event NS_AVAILABLE_IOS(3_0);

UIEventSubtype 是一組枚舉值,其中 UIEventSubtypeMotionShake = 1 就代表搖晃:

typedef NS_ENUM(NSInteger, UIEventSubtype) {
    UIEventSubtypeNone = 0,
    UIEventSubtypeMotionShake = 1,          // iOS 3.0
    UIEventSubtypeRemoteControlPlay = 100,  // iOS 4.0 起
    UIEventSubtypeRemoteControlPause = 101,
    UIEventSubtypeRemoteControlStop = 102,
    UIEventSubtypeRemoteControlTogglePlayPause = 103,
    UIEventSubtypeRemoteControlNextTrack = 104,
    UIEventSubtypeRemoteControlPreviousTrack = 105,
    UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
    UIEventSubtypeRemoteControlEndSeekingBackward = 107,
    UIEventSubtypeRemoteControlBeginSeekingForward = 108,
    UIEventSubtypeRemoteControlEndSeekingForward = 109,
};

除了搖晃,這組枚舉還涵蓋耳機線控的各種按鍵事件,值得一起記住。

實作步驟

建立單視圖應用後,新增一個 UIView 子類(例如 shakeView),把它設為 view controller 的根視圖,然後覆寫 canBecomeFirstResponder 回傳 YES。

/*
 1. 視圖出現在螢幕上時,讓它成為第一響應者
 2. 視圖離開螢幕、App 切到背景或換頁時,取消第一響應者身份
 3. 監聽搖晃事件
 */
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.view becomeFirstResponder];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.view resignFirstResponder];
}

#pragma mark - 監聽運動事件
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (UIEventSubtypeMotionShake == motion) {
        NSLog(@"The view is shake.");
    }
}

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (UIEventSubtypeMotionShake == motion) {
        NSLog(@"搖晃結束");
    }
}

如果不確實在 viewDidDisappear 裡取消第一響應者身份,離開這個畫面之後搖晃仍然會觸發原本的事件,這是常見的 bug 來源。

在模擬器測試

模擬器沒有實體可以搖,改用選單 Hardware → Shake Gesture 即可觸發。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved