Detect touch globally

前端 未结 2 2024
遇见更好的自我
遇见更好的自我 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:24

    If you must include the code detection in your uiimageview subclass then I would tell the appdelegate that a touch was received and where. The app delegate could then either tell all your uiimageviews or tell the viewcontroller which would tell it's uiimageviews.

    untested code:

    appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate touchedAt:(int)xPos yPos:(int)yPos];
    
    0 讨论(0)
  • 2021-01-06 04:29

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

    //  CustomUIWindow.h
    #import <UIKit/UIKit.h>
    
    #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.

    0 讨论(0)
提交回复
热议问题