我有一个父 UIView 和一个子 UIView,我想让触摸从子视图传递到父视图,并由两个视图处理。
y--------------
| parent |
| x------ |
| |child| |
| |_____| |
|_____________|
Run Code Online (Sandbox Code Playgroud)
所以在子视图中,我覆盖:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// child touch handle
// ...
// parent touch handle
[self.nextResponder touchesBegan:touches withEvent:event];
}
Run Code Online (Sandbox Code Playgroud)
谢谢@Fogmeister。就是这样。
UITouch 现在可以传递给父级。在父母的touchesBegan,打电话
[touch locationInView:self]
Run Code Online (Sandbox Code Playgroud)
获取触摸位置。
翻译:博士
\n\n不要进行任何转换,只需使用 locationInView: 方法。
\n\n长版
\n\n为此,您可以使用代码 locationInView: 像这样......
\n\nUITouch *touch = [touches anyObject]; //assuming there is just one touch.\n\nCGPoint touchPoint = [touch locationInView:someView];\nRun Code Online (Sandbox Code Playgroud)\n\n这会将触摸的屏幕坐标转换为您传入的视图中的坐标。
\n\n即,如果用户点击子视图中的点 (10, 10),然后将其传递给下一个响应者,即父视图。当您运行 [touch locationInView:parentView] 时,您将得到一个类似于 (60, 60) 的点(从图表中粗略猜测)。
\n\nlocationInView 的 UITouch 文档
\n\nlocationInView:\n返回接收器在给定视图的坐标系中的当前位置。
\n\n-(CGPoint)locationInView:(UIView *)视图
\n\n参数
\n\n看法
\n\n您希望触摸位于其坐标系中的视图对象。处理触摸的自定义视图可以指定 self 以获取其自己的坐标系中的触摸位置。传递 nil 来获取 window\xe2\x80\x99s 坐标中的触摸位置。
\n\n返回值
\n\n指定视图中接收器位置的点。
\n\n讨论
\n\n此方法返回 UITouch 对象在指定视图的坐标系中的当前位置。由于触摸对象可能已从另一个视图转发到一个视图,因此此方法执行触摸位置到指定视图的坐标系的任何必要转换。
\n\n例子
\n\n你有一个名为parentView框架(0,0,320,480)的视图,即整个屏幕。它有一个称为 childView 框架 (50, 50, 100, 100) 的子视图。
\n\n在子视图中
\n\n- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event\n{\n UITouch *touch = [touches anyObject];\n\n CGPoint touchLocation = [touch locationInView:self];\n\n NSLog(@"Child touch point = (%f, %f).", touchLocation.x, touchLocation.y);\n\n [self.nextResponder touchesBegan:touches withEvent:event];\n}\nRun Code Online (Sandbox Code Playgroud)\n\n在父视图中
\n\n- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event\n{\n UITouch *touch = [touches anyObject];\n\n CGPoint touchLocation = [touch locationInView:self];\n\n NSLog(@"Parent touch point = (%f, %f).", touchLocation.x, touchLocation.y);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n*现在...
\n\n用户在子视图的正中心按下屏幕。
\n\n程序的输出将是...
\n\nChild touch point = (50, 50). //i.e. this is the center of the child view relative to the **child view**.\nParent touch point = (150, 150). //i.e. this is the center of the child view relative to the **parent view**.\nRun Code Online (Sandbox Code Playgroud)\n\n我根本没有做过任何转换。locationInView 方法为您完成这一切。我认为你试图让事情变得过于复杂。
\n| 归档时间: |
|
| 查看次数: |
1542 次 |
| 最近记录: |