Ios 当点击其他地方时,Dragable UIImageView正在进行远程传输

Ios 当点击其他地方时,Dragable UIImageView正在进行远程传输,ios,uiimageview,Ios,Uiimageview,下面的代码基于如何使UIImageView能够在ViewController中拖动的思想。然而,当我使用这个代码时,我点击一个不同的位置,而不是按下图像,它会传送到那个位置,而不是要求我一直拖动图像。我希望下面的代码仅在按下特定图像时有效。请帮忙- -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [[event allTouches] anyObject];

下面的代码基于如何使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];
}

这是远程传送,因为你没有任何检查用户是否确实触摸了图像,所以任何触摸都会导致图像跳转到该位置。您需要做的是检查用户是否触摸过图像,然后仅在用户触摸过图像时移动图像。在ViewController中尝试以下代码,假设“image”是可拖动的视图:

您需要在ViewController上创建一个变量/属性,以跟踪是否正在拖动视图。如果您只需要一个图像,可以使用
BOOL
(下面的代码假设您已经完成了此操作,称为
isDraging


此代码基本上执行签入
触摸开始
,如果您在图像内部触摸,则将属性设置为true;如果您的初始触摸是在图像上,则将其移动到
触摸移动
,最后取消签入
触摸取消

为什么不使用连接到图像视图的平移手势识别器?只有当原始触摸在图像视图上时,才会调用其操作方法。很高兴能提供帮助:)记住,如果答案解决了您的问题,请接受答案。
-(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;
}