搖一搖是常見的互動手法——抽獎、換歌、Undo。iOS 提供兩條路徑:一是直接用系統的 motion 事件,二是透過 CoreMotion 自行判斷加速度。兩者的適用情境不同。
首先在 AppDelegate 中開啟搖動編輯的支援:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 啟用搖動偵測
application.applicationSupportsShakeToEdit = YES;
return YES;
}
接著在需要偵測的 ViewController 中,讓自己成為第一回應者並實作 motion 回呼:
// 讓本控制器能接收搖動事件
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[self resignFirstResponder];
[super viewWillDisappear:animated];
}
// 搖動結束時的回呼
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
if (motion == UIEventSubtypeMotionShake) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示"
message:@"恭喜你獲得 100-5 優惠券一張"
delegate:self
cancelButtonTitle:@"關閉"
otherButtonTitles:nil];
[alertView show];
NSLog(@"檢測到晃動");
}
}
這種做法的優點是極簡、系統原生;缺點是**只有搖動幅度足夠大時才會觸發**,且無法自訂靈敏度。
引入頭文件:
#import <CoreMotion/CoreMotion.h>
在 viewDidLoad 中初始化 CMMotionManager,並啟動一個 NSTimer 持續取樣:
- (void)viewDidLoad {
[super viewDidLoad];
NSTimer *autoTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 60.0
target:self
selector:@selector(autoChange)
userInfo:nil
repeats:YES];
_manager = [[CMMotionManager alloc] init];
_manager.accelerometerUpdateInterval = 1.0 / 60.0;
[_manager startAccelerometerUpdates];
}
- (void)autoChange {
// 可依需求調整 x / y / z 的閾值
if (fabsf(_manager.accelerometerData.acceleration.x) > 1.0 ||
fabsf(_manager.accelerometerData.acceleration.y) > 1.2 ||
fabsf(_manager.accelerometerData.acceleration.z) > 0.5) {
NSLog(@"我晃動了……");
}
}
這種做法的好處是**閾值完全自訂**,可以做出「輕輕一晃」與「用力甩動」的不同反應;也能同時取得陀螺儀資料做更複雜的手勢判斷。
· 只是想實作「搖一搖」,且不需要調整靈敏度 → 用方法一,程式碼最少。
· 需要自訂靈敏度、或要區分不同強度的動作 → 用方法二。
1. 別用 NSTimer 輪詢加速度計。60 fps 的 timer 會讓 CPU 持續醒著,非常耗電。CMMotionManager 本身支援 startAccelerometerUpdatesToQueue:withHandler:,由系統在資料就緒時回呼,不需要自己輪詢:
[_manager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue]
withHandler:^(CMAccelerometerData *data, NSError *error) {
if (fabs(data.acceleration.x) > 1.0) { /* ... */ }
}];
2. 記得停止更新。在 viewDidDisappear 或 dealloc 中呼叫 [_manager stopAccelerometerUpdates],並 invalidate timer,否則會持續耗電甚至造成循環參照。
3. 需要去抖動。一次搖動會產生連續多筆超標樣本,若不加上冷卻時間(例如 1 秒內只觸發一次),抽獎畫面會被連續彈出十幾次。
4. 若使用 UIAlertView 請留意版本。UIAlertView 自 iOS 8 起已被 UIAlertController 取代並在 iOS 9 後標記為 deprecated,新專案請直接使用 UIAlertController。