2012-10-08 38 views
3

應用程序委託是一個UIResponder子類(自Xcode 4.2以來),所以它應該能夠接收觸摸和動作事件。我說這在我AppDelegate類,但它不工作:我可以在我的AppDelegate中收到搖動事件嗎?

-(BOOL)canBecomeFirstResponder 
{ 
    return YES; 
} 

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

它在視圖當然控制器的工作,但我想檢測震動的應用範圍。

+0

是的,你可以,但真正的問題是......我可能錯過了爲什麼你的_app委託人應該參與響應任何用戶交互...?這是一個相當奇怪的建築... – holex

+1

@holex我想擺動手勢在應用程序的每個屏幕上工作。示例用法:搖動以截圖或報告測試版本的反饋。 – Felix

回答

0

就我所知,它應該成爲接收事件的第一響應者。 如果你的應用程序有UINavigationController或UITabController,也許你可以嘗試在那裏接收它。

3

這樣做:

- (void)applicationDidBecomeActive:(UIApplication *)application 
{ 
    [self becomeFirstResponder]; 

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

    NSLog(@"motionBegan"); 

} 

-(BOOL)canBecomeFirstResponder { 
return YES; 
} 
+0

我不知道爲什麼這是downvoted。我試過這種方法,它的工作原理(iOS 7)...任何人都知道這是否會導致任何問題? – JakubKnejzlik

+0

對我也很完美!謝謝! –

2

我擴展UIApplication類,並添加此類引用主: MyApplication.h

@interface MyApplication : UIApplication 

@end 

MyApplication.m

@implementation MyApplication 

- (void) sendEvent:(UIEvent *)event 
{ 
    if(event && (event.subtype==UIEventSubtypeMotionShake)) 
    { 
     AppDelegate *objAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; 

     [objAppDelegate doWhatEver]; 
     [super sendEvent:event]; 
    } 
    else 
    { 
     [super sendEvent:event]; 
    } 
} 

@end 

再上一個臺階in main.m

int main(int argc, char *argv[]) 
{ 
return UIApplicationMain(argc, argv, NSStringFromClass([MyApplication class]), NSStringFromClass([AppDelegate class])); 
} 

這適用於所有情況。

相關問題