1

我有一个父 UIView 和一个子 UIView,我想让触摸从子传递到父,并由两个视图处理。

y--------------
| parent      |
|   x------   |
|   |child|   |
|   |_____|   |
|_____________|

所以在子视图中,我覆盖:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // child touch handle 
    // ...
    // parent touch handle
    [self.nextResponder touchesBegan:touches withEvent:event];
}
但是当我触摸孩子中的“x”时,它会转发给父母中的“y”(相对于父母)。我想要一个通过效果(孩子中的`x`,父母中的`x`),所以我需要在转发之前更改触摸的位置,对吗?我该怎么做?

谢谢@Fogmeister。就是这样。

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

[touch locationInView:self]

获取触摸位置。

4

1 回答 1

4

TL:博士

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

长版

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

UITouch *touch = [touches anyObject]; //assuming there is just one touch.

CGPoint touchPoint = [touch locationInView:someView];

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

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

locationInView 的 UITouch 文档

locationInView:返回给定视图坐标系中接收器的当前位置。

-(CGPoint)locationInView:(UIView *)view

参数

看法

您希望触摸位于其坐标系中的视图对象。处理触摸的自定义视图可以指定 self 以在其自己的坐标系中获取触摸位置。传递 nil 以获取窗口坐标中的触摸位置。

返回值

指定接收器在视野中的位置的点。

讨论

此方法返回 UITouch 对象在指定视图坐标系中的当前位置。因为触摸对象可能已经从另一个视图转发到一个视图,所以此方法执行任何必要的触摸位置到指定视图坐标系的转换。

例子

您有一个名为 parentView frame (0, 0, 320, 480) 的视图,即整个屏幕。这有一个名为 childView frame (50, 50, 100, 100) 的子视图。

在子视图中

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];

    CGPoint touchLocation = [touch locationInView:self];

    NSLog(@"Child touch point = (%f, %f).", touchLocation.x, touchLocation.y);

    [self.nextResponder touchesBegan:touches withEvent:event];
}

在父视图中

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];

    CGPoint touchLocation = [touch locationInView:self];

    NSLog(@"Parent touch point = (%f, %f).", touchLocation.x, touchLocation.y);
}

*现在...

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

该程序的输出将是...

Child touch point = (50, 50). //i.e. this is the center of the child view relative to the **child view**.
Parent touch point = (150, 150). //i.e. this is the center of the child view relative to the **parent view**.

我根本没有进行任何转换。方法 locationInView 为您完成所有这些工作。我认为您正试图使其复杂化。

于 2013-01-03T15:58:37.567 回答