I have a view (parent
) with two subviews, one on top (topChild
) of the other (bottomChild
).
If I tap on the screen only topChild
and parent
receive the touch event.
What should I change to propagate the touch event to bottomChild
as well?
The code:
- (void)viewDidLoad
{
[super viewDidLoad];
MYView* parent = [[MYView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
parent.tag = 3;
parent.backgroundColor = [UIColor redColor];
MYView* bottomChild = [[MYView alloc] initWithFrame:CGRectMake(0, 0, 90, 90)];
bottomChild.tag = 2;
bottomChild.backgroundColor = [UIColor blueColor];
[parent addSubview:bottomChild];
MYView* topChild = [[MYView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
topChild.tag = 1;
topChild.backgroundColor = [UIColor greenColor];
[parent addSubview:topChild];
[self.view addSubview:parent];
}
Where MYView
is a subclass of UIView
that only logs touchesBegan
.
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"%d", self.tag);
[super touchesBegan:touches withEvent:event];
}
The result:
Touching the green area produces the following log:
TouchTest[25062:f803] 1
TouchTest[25062:f803] 3
My first idea was to make parent
propagate all the touchesSomething
calls to its children but (A) I suspect there might be an easier solution and (B) I don't know which child sent the event to parent, and sending touchesSomething
messages twice to the same view might cause shenanigans.
After asking the question I've found this post that suggests to override hitTest
to change the view that receives the touches. I will try this approach and update the question if it works.