ios - 有没有全局性的感动事件?

标签 ios ios5 xamarin.ios

有没有办法监听全局触摸事件?我想在触摸屏幕时收到通知。现在我正在覆盖我的 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/

相关文章:

xamarin - GetViewForAnnotation 从未被调用

ios - Swift:让 SearchBar 搜索这两个部分而不是将它们组合起来

ios - 核心数据保存不持久

iphone - iOS 5 中的 UIKeyboardType 数字键盘返回或完成按钮

objective-c - 在应用程序中禁用 iOS 5 通知中心手势

iphone - 如何配置 MvvmCross 以持久化缓存图像

ios - 刷新 View 背景色

ios - 从 SKTileMapNode 中删除特定图 block

iphone - 来自 Hockey 的 CrashReport,使用 NSPlaceholderDictionary 的尴尬 Stacktrace

xamarin.ios - Xamarin IOS 文件选择器 : unable to get selected file from icloud drive