標籤:class blog code com 2014 os
遇到這樣一個需求:應用無論處於哪個view controller,搖動手機,都能夠出發某一方法。
能夠想到的思路就是用蘋果封裝好的“MotionEvent”,但是如果簡單的把一下代碼加到某一view controller中,那麼只有在該view controller展示在前端時,搖動手機才會出發方法。
- (BOOL)canBecomeFirstResponder {//預設是NO,所以得重寫此方法,設成YES return YES;}然後實現下列方法://很像TouchEvent事件 - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{} - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{ NSLog(@"shake");} - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{}
解決方案:用Category擴充UIWindow,代碼如下:
UIWindow+.h
#import <UIKit/UIKit.h>#define UIEventSubtypeMotionShakeNotification @"UIEventSubtypeMotionShakeNotification"@interface UIWindow (Motion)// @override- (BOOL)canBecomeFirstResponder;- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event;@end
UIWindow+.m
#import "UIWindow+.h"@implementation UIWindow (Motion)- (BOOL)canBecomeFirstResponder {//預設是NO,所以得重寫此方法,設成YES return YES;}然後實現下列方法://很像TouchEvent事件 - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{} - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{ NSLog(@"shake");} - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event{}@end