【发布时间】:2011-12-18 21:54:37
【问题描述】:
我有一个包含两个子视图的视图 (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 将所有touchesSomething 调用传播给它的孩子,但(A)我怀疑可能有更简单的解决方案和(B) 我不知道是哪个孩子将事件发送给了父母,向同一个视图发送两次touchesSomething 消息可能会导致恶作剧。
在提出问题后,我发现这个post 建议覆盖hitTest 以更改接收触摸的视图。如果可行,我会尝试这种方法并更新问题。
【问题讨论】:
标签: iphone ios uiview touchesbegan uiresponder