Need multiple views to respond to a touch event in an iPhone app
-
24-09-2019 - |
Question
Setup: I have two views that I need to respond to the touch event, and they are layered out on top of one another. View 1 is on top of View 2. View 2 is a UIWebView. View 1 is sublclassed to capture the touch event.
My problem is that if I try to call the UIWebView event handlers (touchesBegan: and touchesEnded:) from within the event handlers of View 1, which is the first responder, nothing happens. However if I set View 1 to userInteractionEnabled = NO, then the touch goes through that view and is processed properly by the 2nd view.
Any ideas on how I can have 2 views respond to a touch event? Unfortunately the 2nd view is a UIWebView, so I need to actually call the event handler and not a different method, etc...
Thanks in advance for any advice, Joel
Solution
Here is the solution to my problem. It's working on all kinds of UIView ! If someone whant to improve this code on the
catchUIEventTypeMotion default: ...
I hope that this code will be helpful for you.
PJ.
CustomWindow.h
#import <Foundation/Foundation.h>
@interface CustomWindow : UIWindow {
}
- (void) sendEvent:(UIEvent *)event;
@end
CustomWindow.m
#import "CustomWindow.h"
@implementation CustomWindow
- (void) sendEvent:(UIEvent *)event
{
switch ([event type])
{
case UIEventTypeMotion:
NSLog(@"UIEventTypeMotion");
[self catchUIEventTypeMotion: event];
break;
case UIEventTypeTouches:
NSLog(@"UIEventTypeTouches");
[self catchUIEventTypeTouches: event];
break;
default:
break;
}
/*IMPORTANT*/[super sendEvent:(UIEvent *)event];/*IMPORTANT*/
}
- (void) catchUIEventTypeTouches: (UIEvent *)event
{
for (UITouch *touch in [event allTouches])
{
switch ([touch phase])
{
case UITouchPhaseBegan:
NSLog(@"UITouchPhaseBegan");
break;
case UITouchPhaseMoved:
NSLog(@"UITouchPhaseMoved");
break;
case UITouchPhaseEnded:
NSLog(@"UITouchPhaseEnded");
break;
case UITouchPhaseStationary:
NSLog(@"UITouchPhaseStationary");
break;
case UITouchPhaseCancelled:
NSLog(@"UITouchPhaseCancelled");
break;
default:
NSLog(@"iPhone touched");
break;
}
}
}
- (void) catchUIEventTypeMotion: (UIEvent *)event
{
switch ([event subtype]) {
case UIEventSubtypeMotionShake:
NSLog(@"UIEventSubtypeMotionShake");
break;
default:
NSLog(@"iPhone in movement");
break;
}
}
@end
AppDelegate.h
#import <UIKit/UIKit.h>
#import "CustomWindow.h"
@interface AppDelegate : NSObject <UIApplicationDelegate>
{
CustomWindow *window;
}
@property (nonatomic, retain) IBOutlet CustomWindow *window;
@end