我正在深入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视图中处理它的原因。
你的想法? 非常感谢您的智慧!
答案 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]
(他们会做同样的事情) )。