有没有办法听全球触摸事件?我想在触摸屏幕时收到通知。现在我在我的视图上覆盖了TouchesBegan,但它似乎没有泡沫。即如果我触摸按钮或键盘,方法永远不会被调用。也许通过使用NSNotificationCenter或类似的东西。
谢谢,
答案 0 :(得分:1)
我发布了一些可能有用的代码here。但那段代码很复杂 使用OP的代码,所以这是一个干净的版本。
您可以做的是将UIWindow子类化,并将其作为窗口传递给应用程序委托。
代码看起来像:
<强> 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
协议(实施- (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;
}
答案 1 :(得分:0)
现在我在我的视图上覆盖了TouchesBegan,但事实并非如此 好像它起泡了。
你是对的 - 从视图层次结构的根(即窗口)的视图开始传递触摸,然后向下进行视图层次结构,直到找到触摸的视图。看看UIView的-hitTest:withEvent:
方法。从窗口开始,调用该方法查找命中子视图,然后在子视图上调用相同的方法,依此类推。