如何将子视图上的触摸事件的坐标转换为其父视图中的坐标?

时间:2010-10-30 22:32:05

标签: cocoa-touch uikit ios

我正在深入iOS开发,我正在玩触摸事件。我有一个名为UIPuzzlePiece的类,它是UIImageView的子类,它表示可以在屏幕上移动的拼图块对象。我的目标是能够用手指在屏幕上移动拼图。

目前,我在UIPuzzlePiece类中实现了touchesBegan和touchesMoved事件......

// Handles the start of a touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [[event touchesForView:self] anyObject];
  CGPoint cgLocation = [touch locationInView:self];
  [self setCenter:cgLocation];
}

// Handles the continuation of a touch.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{  
  UITouch *touch = [[event touchesForView:self] anyObject];
  CGPoint cgLocation = [touch locationInView:self];
  [self setCenter:cgLocation];
}

我面临的问题是返回的CGPoint位置代表UIPuzzlePiece视图中的位置,这是有道理的,但我需要知道父视图内触摸的位置。这样,语句[self setCenter:cgLocation]实际上会将UIPuzzlePiece移动到触摸位置。我总是可以编写一些hacky算法来转换它,但我希望有更好或更简单的方法来实现我的目标。如果我只有一个拼图,我只是在父视图的视图控制器中实现触摸事件代码,但我有很多拼图,这就是我在UIPuzzlePiece视图中处理它的原因。

你的想法? 非常感谢您的智慧!

1 个答案:

答案 0 :(得分:4)

UIView实施-convertRect:fromView:-convertRect:toView:-convertPoint:fromView:-convertPoint:toView:。听起来你只需要使用后一种方法之一在视图坐标空间之间进行转换。例如,如果要将CGPoint从self的坐标空间转换为父视图,可以使用[self convertPoint:thePoint toView:self.superview],也可以使用[self.superview convertPoint:thePoint fromView:self](他们会做同样的事情) )。