传送只是因为您没有检查用户是否确实触摸了图像,因此任何触摸都会导致图像跳转到该位置。您需要做的是检查用户是否触摸了图像,然后仅在触摸时才移动它。在 ViewController 中尝试以下代码,假设“图像”是可拖动视图:
您需要在 ViewController 上创建一个变量/属性来跟踪视图是否被拖动。如果您只需要一张图片,您可以使用 a BOOL
(下面的代码假设您已经完成了此操作,称为isDragging
)。
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:image];
if([image pointInside:location withEvent:event]) {
isDragging = YES;
}
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
if(isDragging)
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:self.view];
image.center = location;
[self ifCollided];
}
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
isDragging = NO;
}
如果您在图像内部触摸,此代码基本上会进行签入touchesBegan
并将属性设置为 true,touchesMoved
如果您最初触摸的是图像,则将其移入,最后取消签入touchesEnded
。