我正在学习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