0

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

1 回答 1

0

传送只是因为您没有检查用户是否确实触摸了图像,因此任何触摸都会导致图像跳转到该位置。您需要做的是检查用户是否触摸了图像,然后仅在触摸时才移动它。在 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

于 2013-08-14T00:07:35.577 回答