2012-11-16 24 views
0

这拖动多个UIImageViews的是我到目前为止在Array

-(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)]; 

     } 
} 
} 

回答

5

那是因为您将它们全部移动到同一位置,您需要计算触摸位置之间的差异并将该位移添加到所有视图。下面的代码应该解决你的问题!忘记touchesBegan然后重写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)]; 
     } 
    } 

享受编程!

+0

这真的很好,唯一的情况是我希望图像能够单独移动,现在它们都一起移动。非常感谢。 – Jonathan

+0

@Jonathan分别移动他们看到我编辑的答案,希望有所帮助! –

+0

@Jonathan再次编辑了一些故障!尝试如果解决了你的问题! –

0

在这里,您编码方式类似于只。如果你想移动一个图像,那么你必须找到该图像,你应该单独移动该图像。