Below is the code I'm working with now, it allows the user to drag and drop the image around the screen. You will notice if if statements with values โโset to "960" and "640", which means that if a user tries to drag an image from the screen, he animates the image by moving back to the screen and can be easily resized so that the image moves to the nearest coordinate the grid that the user fell next to.
- (void)callMarkerFourteen { UIImage *image = [UIImage imageNamed:@"VerticalLine.png"]; markerViewFourteen = [[UIView alloc] initWithFrame:CGRectMake(160, 210, 40, image.size.height)]; [markerViewFourteen setBackgroundColor:[UIColor colorWithRed:255 green:0 blue:0 alpha:.5]]; markerImageViewFourteen = [[UIImageView alloc] initWithFrame:[markerViewFourteen frame]]; [markerImageViewFourteen setFrame:CGRectMake(18, 0, 4, 100)]; [markerImageViewFourteen setImage:image]; [markerViewFourteen addSubview:markerImageViewFourteen]; UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)]; [panRecognizer setMinimumNumberOfTouches:1]; [panRecognizer setMaximumNumberOfTouches:1]; [panRecognizer setDelegate:self]; [markerViewFourteen addGestureRecognizer:panRecognizer]; [self.view addSubview:markerViewFourteen]; } -(void)move:(id)sender { [[[(UITapGestureRecognizer*)sender view] layer] removeAllAnimations]; [self.view bringSubviewToFront:[(UIPanGestureRecognizer*)sender view]]; CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view]; if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) { firstX = [[sender view] center].x; firstY = [[sender view] center].y; } translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y); [[sender view] setCenter:translatedPoint]; if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded) { CGFloat finalX = translatedPoint.x + (0.0*[(UIPanGestureRecognizer*)sender velocityInView:self.view].x); CGFloat finalY = translatedPoint.y + (0.0*[(UIPanGestureRecognizer*)sender velocityInView:self.view].y); if(UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) { if(finalX < 0) { finalX = 0; } else if(finalX > 640) { finalX = 640; } if(finalY < 0) { finalY = 0; } else if(finalY > 960) { finalY = 960; } } else { if(finalX < 0) { finalX = 0; } else if(finalX > 960) { finalX = 640; } if(finalY < 0) { finalY = 0; } else if(finalY > 640) { finalY = 960; } } [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:.35]; [UIView setAnimationCurve:UIViewAnimationCurveEaseOut]; [[sender view] setCenter:CGPointMake(finalX, finalY)]; [UIView commitAnimations]; } }
source share