有没有办法监听全局触摸事件?我想在触摸屏幕时收到通知。现在我正在覆盖我的 View 上的 TouchesBegan,但它似乎并没有冒泡。即,如果我触摸按钮或键盘,则该方法永远不会被调用。也许通过使用 NSNotificationCenter 或类似的东西。
谢谢
最佳答案
我发布了一些代码here这可能有帮助。但该代码是混合的 与OP的代码,所以这是一个干净的版本。
您可以做的是子类化 UIWindow 并将其传递给应用程序委托(delegate)作为其窗口。
代码看起来像这样:
MyKindOfWindow.h
#import <UIKit/UIKit.h>
@protocol MyKindOfWindowDelegate;
@interface MyKindOfWindow : UIWindow
@property (assign) id <MyKindOfWindowDelegate> touchDelegate;
@end
@protocol MyKindOfWindowDelegate <NSObject>
@required
- (void) windowTouch:(UIEvent *)event;
@end
MyKindOfWindow.m
#import "MyKindOfWindow.h"
@implementation MyKindOfWindow
@synthesize touchDelegate = _touchDelegate;
- (id)initWithFrame:(CGRect)aRect
{
if ((self = [super initWithFrame:aRect])) {
_touchDelegate = nil;
}
return self;
}
- (void)sendEvent:(UIEvent *)event
{
[super sendEvent: event];
if (event.type == UIEventTypeTouches)
[_touchDelegate windowTouch:event];
}
@end
您的 AppDelegate
当然需要遵循 MyKindOfWindowDelegate
协议(protocol)(实现 - (void) windowTouch:(UIEvent *)event
方法)。
didFinishLaunchingWithOptions:
看起来像:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[MyKindOfWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
[(MyKindOfWindow *)self.window setTouchDelegate:self]; //!!make your AppDelegate a delegate of self.window
//this part of code might be different for your needs
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil];
} else {
self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil];
}
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
关于ios - 有没有全局性的感动事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10502134/