Search code examples
iphoneiosuiimageviewtouchesmoved

Have Multiple Moving UIImage Views With Different Touches


I am working on trying to get multiple UIImageViews to move when they are dragged. I was originally putting all the movement under TouchesBegan. However, when I drag a single object, they all disappear and only the one I am dragging moves.

How can I have each image dragged own its own terms(I drag the first image, only the first image moves etc.)?


Solution

  • I'm not sure if this is what you're looking for but I worked on this a while ago, so hopefully it's useful.

    Just make sure you set up 7 UIImageViews in the XIB File, link them and you'll be good to go.

    @synthesize img1, img2, img3, img4, img5, img6, magnet;
    
    -(void) checkInsertion {
        if (CGRectContainsRect(img2.frame, img1.frame)) {img1.center = img2.center;}
        if (CGRectContainsRect(img4.frame, img3.frame)) {img3.center = img4.center;}
        if (CGRectContainsRect(img6.frame, img5.frame)) {img5.center = img6.center;}
    
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.2];
        if (CGRectIntersectsRect(magnet.frame, img1.frame)) {img1.center = magnet.center;}
        if (CGRectIntersectsRect(magnet.frame, img2.frame)) {img2.center = magnet.center;}
        if (CGRectIntersectsRect(magnet.frame, img3.frame)) {img3.center = magnet.center;}
        if (CGRectIntersectsRect(magnet.frame, img4.frame)) {img4.center = magnet.center;}
        if (CGRectIntersectsRect(magnet.frame, img5.frame)) {img5.center = magnet.center;}
        if (CGRectIntersectsRect(magnet.frame, img6.frame)) {img6.center = magnet.center;}
        [UIView commitAnimations];
    
    }
    
    -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch * touch = [[event allTouches] anyObject];
        CGPoint touchLoc = [touch locationInView:touch.view];
    
        if (CGRectContainsPoint(img1.frame, touchLoc)) {img1.center = touchLoc;}
        if (CGRectContainsPoint(img3.frame, touchLoc)) {img3.center = touchLoc;}
        if (CGRectContainsPoint(img5.frame, touchLoc)) {img5.center = touchLoc;}
    
        if (CGRectContainsPoint(magnet.frame, touchLoc)) {magnet.center = touchLoc;}
    
        [self checkInsertion];
    }
    
    -(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        [self touchesBegan:touches withEvent:event];
    }