【发布时间】:2010-10-30 22:32:04
【问题描述】:
我正在深入研究 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参数? -
因为我是菜鸟,谢谢指出!
标签: cocoa-touch uikit ios