0

グローバルタッチイベントを聞く方法はありますか?画面をタッチしたときに通知を受け取りたいです。現在、ビューでTouchesBeganをオーバーライドしていますが、バブルが発生していないようです。つまり、ボタンまたはキーボードに触れても、メソッドが呼び出されることはありません。たぶんNSNotificationCenterまたは同様のものを使用することによって。

ありがとう、

4

2 に答える 2

1

ここに役立つコードをいくつか投稿しました。しかし、そのコードは 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;
}
于 2012-05-08T20:12:37.783 に答える
0

現在、ビューで TouchesBegan をオーバーライドしていますが、バブルアップしているようには見えません。

その通りです。タッチは、ビュー階層のルート (つまり、ウィンドウ) のビューから開始され、タッチされたビューが見つかるまでビュー階層を下っていきます。UIView の-hitTest:withEvent:メソッドを見てみましょう。ウィンドウから始めて、ヒットしたサブビューを見つけるためにそのメソッドが呼び出され、サブビューで同じメソッドが呼び出されます。

于 2012-05-08T20:40:28.080 に答える