Creating Draggable Images

Discussion in 'iOS Programming' started by ahan.tm, Aug 20, 2011.

  1. ahan.tm macrumors regular

    Joined:
    Jun 26, 2011
    Location:
    Florida
    #1
    Hi,

    I am stuck while trying to create multiple draggable UIImageViews in Xcode 4. I am also trying to get them to have an action when the collide with another UIImageView.

    Thanks!
     
  2. xcodeNewbie macrumors member

    Joined:
    Jul 1, 2011
    #2
    Dragging Images

    Creating draggable images and collision testing with them shouldn't be too hard, but it will require quite a bit of code (enough so that I'm not going to post it all). Read up on UIGestureRecognizers. In particular, pay attention to the UIPanGestureRecognizer, it's what's used to detect dragging on the screen.
    Edit: As for collision testing, throw all of your imageViews into an array and then loop through them all to see if any of them touch.
     
  3. ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #3
    Using CGRectIntersectsRect(image1.frame, image2.frame)

    where image1 and image 2 are the names of your images will be very useful to you in collision detections.
     
  4. ahan.tm thread starter macrumors regular

    Joined:
    Jun 26, 2011
    Location:
    Florida
    #4
    Hi,

    I have had some luck when using the code below:
    Code:
    -(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    	UITouch *touch = [[event allTouches] anyObject];
    	CGPoint location = [touch locationInView:touch.view];
    	add1.center = location;
        
    }
    
    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    	[self touchesBegan:touches withEvent:event];
    }
    
    But now, I do not know how to apply this code to multiple images. . .
     
  5. ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #5
    Rather than simply accept the touch, have it check which image the touch is inside of. Something like CGRectContainsPoint(img1.frame, location) will check if the touch location is within the frame of image 1.
     

Share This Page