我正在深入研究 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 View 内的位置,这是有道理的,但我需要知道触摸在父 View 内的位置。这样语句 [self setCenter:cgLocation]
实际上会将 UIPuzzlePiece 移动到触摸的位置。我总是可以编写一些 hacky 算法来转换它,但我希望有更好或更简单的方法来实现我的目标。如果我只有一个拼图,我会在父 View 的 View Controller 中实现触摸事件代码,但我有很多拼图,这就是为什么我在 UIPuzzlePiece View 中处理它。
你的想法? 非常感谢您的智慧!
最佳答案
UIView 实现 -convertRect:fromView:
、-convertRect:toView:
、-convertPoint:fromView:
和 -convertPoint:查看:
。听起来您只需要使用后一种方法即可在 View 坐标空间之间进行转换。例如,如果你想将一个 CGPoint 从 self
的坐标空间转换到父 View ,你可以使用 [self convertPoint:thePoint toView:self.superview]
或者您可以使用 [self.superview convertPoint:thePoint fromView:self]
(它们会做同样的事情)。
关于cocoa-touch - 如何将 subview 上触摸事件的坐标转换为其父 View 中的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4060964/