将触摸事件传递给所有子视图的最佳方式是什么?
ViewController -> 视图 -> (subview1, subview2)
我希望 subview1 和 subview2 都响应触摸事件。
将子视图上的标签设置为显着标签。然后在视图中进行树搜索以查找这些标签。不幸的是,没有子类化并没有真正好的方法来做到这一点。如果您愿意子类化,那么您将子类化视图,然后在触摸时抛出一个 NSNotification,该子类的所有其他视图都会监听。
在父级的触摸处理程序中,您可以遍历该视图的子视图并调用相同的处理程序:
- (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
}