2011-04-03 25 views
0

我無法在iPhone上獲得搖動事件。無法在iPhone上獲得搖動事件

我在這裏跟着其他問題沒有結果。我也嘗試過遵循Apple的GLPaint示例,但它看起來與我的源代碼完全相同,只是有一點不同。 GLPaint的源代碼/ works /,mine /不會/。

所以,這裏是我:

Controller.m或者

- (void)awakeFromNib { 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shakeEnded) name:@"shake" object:nil]; 
} 

ShakingEnabledWindow.m

- (void)shakeEnded { 
    NSLog(@"Shaking ended."); 
} 

- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event { 
} 

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { 
    if (motion == UIEventSubtypeMotionShake) { 
     // User was shaking the device. Post a notification named "shake". 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"shake" object:self]; 
     NSLog(@"Shaken!"); 
    } 
} 

- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event { 
} 

我的廈門國際銀行有一個窗口,這是一個ShakingEnabledWindow和對象,我的控制器。

我在這裏想法不多,希望有人能幫我一把。 :)

+0

你是否試圖讓它與'View'或'ViewController'一起工作? – FreeAsInBeer 2011-04-03 22:16:15

+0

在窗口中,如下所示:http://developer.apple.com/library/ios/#samplecode/GLPaint/Introduction/Intro.html – MegaEduX 2011-04-03 22:16:56

回答

0

我認爲你錯誤地檢查運動類型。你需要覈對event.subtype而不是motion

-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event { 
    if (event.subtype == UIEventSubtypeMotionShake) { 
     // Put in code here to handle shake 
    } 
} 
+0

仍然無法正常工作。 – MegaEduX 2011-04-03 22:12:59

+0

@MegaEduX:你有沒有嘗試我的原始代碼,或我修改過的答案? – FreeAsInBeer 2011-04-03 22:14:18

+0

我也試過event.subtype。蘋果的例子檢查運動,這就是爲什麼我使用它。無論如何,嘗試了它,沒有工作。 – MegaEduX 2011-04-03 22:16:12

1

NSNotificationCenter的文件說:

的addObserver:選擇:名稱:對象: notificationSelector選擇器 指定該消息的接收器 發送notificationObserver通知 它的通知發佈。 指定的方法 notificationSelector 必須有一個和 只有一個參數( NSNotification的一個實例)。

所以你的shakeEnded方法是錯誤的,因爲它不需要參數。它應該是:

- (void)shakeEnded:(NSNotification*)notiication { 
    NSLog(@"Shaking ended."); 
} 

- (void)awakeFromNib { 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shakeEnded:) name:@"shake" object:nil]; 
} 
+0

同樣的結果.... – MegaEduX 2011-04-03 22:12:05

1

viewDidAppear,成爲第一個響應者:

- (void)viewDidAppear:(BOOL)animated { 
    [super viewDidAppear:animated]; 
    [self becomeFirstResponder]; 
} 

並確保你可以第一個響應者:

- (BOOL)canBecomeFirstResponder { 
    return YES; 
} 

然後你就可以實現運動檢測。

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event 
{ 
    if (event.subtype == UIEventTypeMotion){ 
     //there was motion 
    } 
} 
+0

event.subtype和motion在我的測試中是一樣的。 – 2011-07-06 19:09:20