Search code examples
iphoneiosxcodeuiimageviewuitouch

how to add on touch and detect UIImageView on view so i could move it around and not adding one on top of it?


i wonder if you guys have a sample code adding and move UIImageView on touch and also detect if there is an UIImageView there so i can't add UIImageView on top of it.

EDIT: clearer question 1. i wanna add an cups(UIImageView) when i touch the view but do not wan the cup(UIImageView) to stack.

  1. i wanna move the UIImageView but will bounce back to the original position if there is an UIImageView there so it will not stack the UIImageView already there.

thanks for reading my question and appreciated your helps

cheers

des


Solution

  • This should let you going…

    Create two ivars in your header file:

    UIImageView *myImageView1;
    UIImageView *myImageView2;
    

    The next two methods will be in your implementation file:

    -(void)initImagesAndPanGesture
    {
        UIImage *img = [UIImage imageNamed:@"image1.png"];
        myImageView1 = [[UIImageView alloc]initWithImage:img];
        [myImageView1 setFrame:CGRectMake(300, 800, 100, 100)];
        [myImageView1 setUserInteractionEnabled:YES];
        UIPanGestureRecognizer *recognizer1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan1:)];
        [myImageView1 addGestureRecognizer:recognizer1];
        [self.view addSubview:myImageView1];
    
        img = [UIImage imageNamed:@"image2.png"];
        myImageView2 = [[UIImageView alloc]initWithImage:img];
        [myImageView2 setFrame:CGRectMake(500, 800, 100, 100)];
        [myImageView2 setUserInteractionEnabled:YES];
        recognizer1 = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan1:)];
        [myImageView2 addGestureRecognizer:recognizer1];
        [self.view addSubview:myImageView2];
    }
    
    -(void)handlePan1:(UIPanGestureRecognizer *)recognizer
    {
        if (!(CGRectIntersectsRect(myImageView1.frame, myImageView2.frame)))
        {
            CGPoint translation = [recognizer translationInView:self.view];
            recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, 
                                             recognizer.view.center.y + translation.y);
    
            [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
        }
        else 
        {
            NSLog(@"intersect!");
        }
    }