下面的代码基于如何使UIImageView能够在ViewController中拖动的想法。然而,当我使用这个代码时,我点击一个不同的位置,而不是按下图像,它传送到该位置,而不是要求我总是拖动图像。我希望下面的代码仅在按下该特定图像时才起作用。请帮助 -
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];
image.center = location;
[self ifCollided];
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[self touchesBegan:touches withEvent:event];
}
答案 0 :(得分:0)
传送仅仅是因为您没有检查用户是否实际触摸过图像,因此任何触摸都会导致图像跳转到该位置。您需要做的是检查用户是否触摸了图像,然后仅在他们有图像时移动它。在ViewController中尝试以下代码,假设'image'是可拖动的视图:
您需要在ViewController上创建一个变量/属性,以跟踪是否正在拖动视图。如果您只需要一张图片,则可以使用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
。