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

3

我正在学习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视图中处理它的原因。
你有什么想法吗? 非常感谢您的智慧!

为什么你要请求 [event touchesForView:self] 而不是直接使用提供的 touches 参数? - Lily Ballard
因为我是新手,感谢你指出来! - BeachRunnerFred
1个回答

4

UIView实现了-convertRect:fromView:, -convertRect:toView:, -convertPoint:fromView:-convertPoint:toView:方法。这些方法可以在不同的视图坐标空间之间进行转换。例如,如果您想要将CGPoint从self的坐标空间转换为其父视图的坐标空间,您可以使用[self convertPoint:thePoint toView:self.superview]或者[self.superview convertPoint:thePoint fromView:self](它们会做相同的事情)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接