Detect touch globally

前端 未结 2 2042
遇见更好的自我
遇见更好的自我 2021-01-06 03:49

I trying to figure out how to solve this (fairly) simple problem but I failing miserably, so I really need your advice.

My application consists of a uitabbar with se

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-06 04:29

    To catch all touch events globally I ended up subclassing UIWindow as follows:

    //  CustomUIWindow.h
    #import 
    
    #define kTouchPhaseBeganCustomNotification @"TouchPhaseBeganCustomNotification"
    
    @interface CustomUIWindow : UIWindow
    @property (nonatomic, assign) BOOL enableTouchNotifications;
    @end
    
    //  CustomUIWindow.m
    #import "CustomUIWindow.h"
    
    @implementation CustomUIWindow
    
    @synthesize enableTouchNotifications = enableTouchNotifications_;
    
    - (void)sendEvent:(UIEvent *)event
    {
        [super sendEvent:event];  // Apple says you must always call this!
    
        if (self.enableTouchNotification) {
            [[NSNotificationCenter defaultCenter] postNotificationName:kTouchPhaseBeganCustomNotification object:event];
        }
    }@end
    

    Then whenever I need to start listening to all touches globally I do the following:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(stopThumbnailWobble:)
                                                 name:kTouchPhaseBeganCustomNotification
                                               object:nil];
    
    ((CustomUIWindow *)self.window).enableTouchNotification = YES;   
    

    In stopThumbnailWobble I remove the observer and process the UITouch event to decide whether to remove the thumb or not:

    - (void)stopThumbnailWobble:(NSNotification *)event
    {    
        [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                        name:kTouchPhaseBeganCustomNotification 
                                                      object:nil];
        ((CustomUIWindow *)self.window).enableTouchNotification = NO;
    
        UIEvent *touchEvent = event.object;
        // process touchEvent and decide what to do
        ...
    

    Hope this helps others.

提交回复
热议问题