標籤:
搖一搖功能的實現
在AppStore中多樣化功能越來越多的被使用了,所以今天就開始介紹一些iOS開發的比較實用,但是我們接觸的比較少的功能,我們先從搖一搖功能開始
在 UIResponder中存在這麼一套方法
1 - (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);2 3 - (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);4 - (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
這就是執行搖一搖的方法。那麼怎麼用這些方法呢?
很簡單,你只需要讓這個Controller本身支援搖動
同時讓他成為第一相應者:
1 - (void)viewDidLoad 2 3 4 { 5 6 7 [superviewDidLoad]; 8 9 10 // Do any additional setup after loading the view, typically from a11 nib.12 13 14 [[UIApplicationsharedApplication]15 setApplicationSupportsShakeToEdit:YES];16 17 18 [self19 20 21 becomeFirstResponder];22 23 24 }
然後去實現那幾個方法就可以了
1 - (void) motionBegan:(UIEventSubtype)motion 2 withEvent:(UIEvent 3 4 5 *)event 6 7 8 { 9 10 11 //檢測到搖動12 13 14 }15 16 17 - (void) motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent18 *)event19 20 21 {22 23 24 //搖動取消25 26 27 }28 29 30 31 - (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent32 *)event33 34 35 36 {37 38 39 //搖動結束40 41 42 if43 (event.subtype == UIEventSubtypeMotionShake) {44 45 46 //something47 happens48 49 50 51 }52 53 54 }
下面我們開始簡單的使用它: 我們只要在控制器裡面實現下面代碼就可以實現搖一搖功能
1 - (void)viewDidAppear:(BOOL)animated 2 { 3 [super viewDidAppear:animated]; 4 [self becomeFirstResponder]; 5 } 6 - (void) viewWillAppear:(BOOL)animated 7 { 8 [self resignFirstResponder]; 9 [super viewWillAppear:animated]; 10 }11 -(BOOL)canBecomeFirstResponder 12 {13 return YES;14 }15 - (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event16 {17 18 if (motion == UIEventSubtypeMotionShake) {19 NSLog(@"搖一搖"); 20 } 21 }
另外值得一提的是,在模擬器中運行時,可以通過「Hardware」-「Shake Gesture」來測試「搖一搖」功能。
iOS開發——進階技術&搖一搖功能的實現