将触摸事件传递给所有子视图的最佳方法是什么?
ViewController - >查看 - > (subview1,subview2)
我想要subview1& subview2都响应触摸事件。
答案 0 :(得分:1)
将子视图上的标记设置为等于标记的标记。然后在树中搜索查找这些标记的视图。不幸的是,没有子类化,没有一个很好的方法可以做到这一点。如果您愿意继承子类,那么您将继承视图,然后触摸一个NSNotification,该同一个子类的所有其他视图都将监听。
答案 1 :(得分:1)
在父级的触摸处理程序中,您可以遍历该视图的子视图并调用相同的处理程序:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
for(UIView *subview in [self.view subviews]) {
[subview touchesBegan:touches withEvent:event];
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
for(UIView *subview in [self.view subviews]) {
[subview touchesMoved:touches withEvent:event];
}
}
或者,如果您需要识别特定的子视图,可以将整数标记分配给子视图以便以后识别它们:
- (void)loadView {
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(10,10,10,10)];
view1.tag = 100;
[self.view addSubview:view1];
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(20,20,20,20)];
view2.tag = 200;
[self.view addSubview:view2];
}
然后在触摸事件调用的ViewController方法中
- (void)touchEventResponder {
UIView *view1 = [self.view viewWithTag:100];
// Do work with view1
UIView *view2 = [self.view viewWithTag:200];
// Do work with view2
}