如何在传递给下一个响应者之前更改 UITouch 的位置

smi*_*lar 1 uiview ios

我有一个父 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) 但是当我触摸子级中的“x”时,它转发到父级中的“y”(相对于父级)。我想要一个传递效果(子级中的“x”,传递到父级中的“x”),所以我需要在转发之前更改触摸的位置,对吗?我该怎么做?

谢谢@Fogmeister。就是这样。

UITouch 现在可以传递给父级。在父母的touchesBegan,打电话

[touch locationInView:self]
Run Code Online (Sandbox Code Playgroud)

获取触摸位置。

Fog*_*ter 5

翻译:博士

\n\n

不要进行任何转换,只需使用 locationInView: 方法。

\n\n

长版

\n\n

为此,您可以使用代码 locationInView: 像这样......

\n\n
UITouch *touch = [touches anyObject]; //assuming there is just one touch.\n\nCGPoint touchPoint = [touch locationInView:someView];\n
Run Code Online (Sandbox Code Playgroud)\n\n

这会将触摸的屏幕坐标转换为您传入的视图中的坐标。

\n\n

即,如果用户点击子视图中的点 (10, 10),然后将其传递给下一个响应者,即父视图。当您运行 [touch locationInView:parentView] 时,您将得到一个类似于 (60, 60) 的点(从图表中粗略猜测)。

\n\n

locationInView 的 UITouch 文档

\n\n

locationInView:\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}\n
Run 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}\n
Run Code Online (Sandbox Code Playgroud)\n\n

*现在...

\n\n

用户在子视图的正中心按下屏幕。

\n\n

程序的输出将是...

\n\n
Child 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**.\n
Run Code Online (Sandbox Code Playgroud)\n\n

我根本没有做过任何转换。locationInView 方法为您完成这一切。我认为你试图让事情变得过于复杂。

\n