0

这是我到目前为止所拥有的

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];

    for (UIImageView *imageView in _imageViewArray) {
            CGPoint Location = [touch locationInView:touch.view];
            imageView.center = Location;
    }   
}

我面临的问题是当我移动一张图像时,它们都会跳到同一个地方。

感谢cyberpawn,这就是我所做的让它工作

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];

    CGPoint oldPoint = [touch previousLocationInView:touch.view];
    CGPoint newPoint = [touch locationInView:touch.view];

    CGPoint diff = CGPointMake(newPoint.x - oldPoint.x, newPoint.y - oldPoint.y);

    for (UIImageView *imageView in _imageViewArray) {
        if (CGRectContainsPoint(imageView.frame, newPoint)) {
            CGPoint cntr = [imageView center];
            [imageView setCenter:CGPointMake(cntr.x + diff.x, cntr.y + diff.y)];

        }
}
}
4

2 回答 2

5

那是因为您将它们全部移动到同一位置,您需要计算触摸位置之间的差异并将该位移添加到所有视图中。下面的代码应该可以解决您的问题!忘记 t​​ouchesBegan 并像这样覆盖 touchesMoved 方法。

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];

    CGPoint oldPoint = [touch previousLocationInView:touch.view];
    CGPoint newPoint = [touch locationInView:touch.view];

    CGPoint diff = CGPointMake(newPoint.x - oldPoint.x, newPoint.y - oldPoint.y);

    for (UIImageView *imageView in _imageViewArray) {
        CGPoint cntr = [imageView center];
        [imageView setCenter:CGPointMake(cntr.x + diff.x, cntr.y + diff.y)];
    }
}

如果您想在单击其中任何一个时单独移动它们,而不是使用下面的代码!

float oldX, oldY;

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint pt = [touch locationInView:touch.view];
    for (UIImageView *imageView in _imageViewArray) {
        if(CGRectContainsPoint(imageView.frame, pt)) {
            oldX = imageView.center.x - imageView.frame.origin.x - pt.x;
            oldY = imageView.center.y - imageView.frame.origin.y - pt.y;
            break;
        }
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint pt = [touch locationInView:touch.view];

    for (UIImageView *imageView in _imageViewArray) {
        if (CGRectContainsPoint(imageView.frame, pt)) {
            [self setCenter:CGPointMake(pt.x+oldX, pt.y+oldY)];
        }
    }

享受编程!

于 2012-11-16T04:43:13.003 回答
0

在这里你只是这样编码。如果要移动单个图像,则必须找到该图像,并且应该单独移动该图像。

于 2012-11-16T04:37:58.663 回答