我有一个带有两个子视图的视图 ( ),一个在另一个 ( ) 的parent
顶部 ( )。topChild
bottomChild
如果我只点击屏幕topChild
并parent
接收触摸事件。
我应该改变什么来传播触摸事件bottomChild
?
编码:
- (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];
}
仅记录MYView
的子类在哪里。UIView
touchesBegan
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(@"%d", self.tag);
[super touchesBegan:touches withEvent:event];
}
结果:
触摸绿色区域会产生以下日志:
TouchTest[25062:f803] 1
TouchTest[25062:f803] 3
我的第一个想法是将所有呼叫parent
传播给它的孩子,但是(A)我怀疑可能有一个更简单的解决方案,并且(B)我不知道哪个孩子将事件发送给父母,并且两次向同一个视图发送消息可能会引起恶作剧。touchesSomething
touchesSomething
在提出问题后,我发现这篇文章建议覆盖hitTest
以更改接收触摸的视图。如果可行,我将尝试这种方法并更新问题。