我试图拖动一个图像,让它在释放后返回原来的位置.到目前为止,我可以使用以下代码将图像创建为按钮来拖动图像:(如此问题的答案中所示:
Basic Drag and Drop in iOS)
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button addTarget:self action:@selector(imageTouch:withEvent:) forControlEvents:UIControlEventTouchDown]; [button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside]; [button setImage:[UIImage imageNamed:@"vehicle.png"] forState:UIControlStateNormal]; [self.view addSubview:button];
后来我定义:
- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event { CGPoint point = [[[event allTouches] anyObject] locationInView:self.view]; UIControl *control = sender; control.center = point; }
如何在释放后将其恢复到原始位置?对于初学者我会保存每个图像应该返回的位置,但是,无论如何,无论如何都要指示UIImage从它的当前位置移动并移动到另一个?或任何其他替代解决方案?
解决方法
你知道吗,我昨天刚刚开始研究这个问题,所以在这里你会得到一些奖励动画:
- (void)previewImageTouchUpInside:(UIButton*)aButton { if (!previewImageDragged) { [self selectPreviewImage:aButton]; return; } previewImageDragged = NO; // If user drag photo a little and then release,we'll still treat it as a tap // instead of drag if ((originalPositionOfButton.x - aButton.center.x) * (originalPositionOfButton.x - aButton.center.x) + (originalPositionOfButton.y - aButton.center.y) * (originalPositionOfButton.y - aButton.center.y) < 10) { aButton.center = originalPositionOfButton; [self selectPreviewImage:aButton]; return; } [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaSEOut | UIViewAnimationOptionAllowUserInteraction animations:^{ aButton.center = originalPositionOfButton; } completion:nil]; } - (void)previewImageDraggedInside:(UIButton*)aButton event:(UIEvent*)event { if (!previewImageDragged) { originalPositionOfButton = aButton.center; [self.view bringSubviewToFront:aButton]; [self.view bringSubviewToFront:[self.view viewWithTag:CHOOSE_PHOTO_BUTTON_TAG]]; } UITouch* touch = [[event allTouches] anyObject]; previewImageDragged = YES; aButton.center = CGPointMake(aButton.center.x+[touch locationInView:self.view].x- [touch prevIoUsLocationInView:self.view].x,aButton.center.y+[touch locationInView:self.view].y- [touch prevIoUsLocationInView:self.view].y); }
它仍然有一些神奇的数字,我没有重命名函数和变量以适合你的例子,但它应该是清楚的.我也在这里做了缩进,因为我没有在我的代码中手动断行长行.