开发者

how to "bypass" touch events in Cocoa-touch?

开发者 https://www.devze.com 2023-02-11 19:19 出处:网络
I want to make a transparent mask-view over the current window, which just tracks touch events and passing them to 开发者_Go百科the visible views below. However if I set userInteractionEnabled=YES to

I want to make a transparent mask-view over the current window, which just tracks touch events and passing them to 开发者_Go百科the visible views below. However if I set userInteractionEnabled=YES to this mask, this blocks the events and won't be passed below.

Is there any way that I can prevent this view from blocking the events, or manually passing the events below?

Thanks,


I just recently did this for one of my apps and it turned out to be quite simple.

Get ready to subclass UIView:

I called my Mask View the catcher view and this is how the protocol looks:

@interface CatcherView : UIView {

    UIView *viewBelow;

}

@property(nonatomic,retain)UIView *viewBelow;

@end

Here you are just subclassing UIView AND keeping a reference to the view bellow.

On the implementation you need to fully implement at least 4 methods to pass the touches to the view, or views bellow, this is how the methods look:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touch Began");
    [self.viewBelow touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touch Moved");
    [self.viewBelow touchesMoved:touches withEvent:event];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touch Ended");

    [self.viewBelow touchesEnded:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"Touch Cancelled");
    //Not necessary for my app but you just need to forward it to your view bellow.
}

Just remember to set the view or views that are bellow when you create the view; it is also very important to set the background color to clear, so it acts as a mask. THis is how that looks:

    CatcherView *catchView=[[CatcherView alloc] initWithFrame:[self.view bounds]];
    catchView.backgroundColor=[UIColor clearColor];
    catchView.viewBelow=myViewBellow;
    [self.view addSubview:catchView];

Hope it helps and comment if you need more info.


  • UIKit determines the target view for an event by sending -hitTest:withEvent: messages down the responder chain
  • Once the target has been found, the event is sent up the responder chain until a responder that handles it is found (often the view that was touched, but not always)

Thus, if you override -[NSView hitTest:withEvent:] in a suitably high up view (perhaps by using a custom window!) you can note all incoming events and call super to have them behave as normal.

0

精彩评论

暂无评论...
验证码 换一张
取 消