xcode 拖放对象并将它们返回到原始位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5627811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:47:44  来源:igfitidea点击:

Drag and drop objects and return them to their original position

iphoneobjective-cxcodedrag-and-drop

提问by José Joel.

I'm trying to drag an image and let it return to it's original position after releasing it. So far, I can drag an image by creating it as a button using the following code: (as seen in the answer to this question: Basic Drag and Drop in iOS)

我正在尝试拖动图像并让它在释放后返回到原始位置。到目前为止,我可以通过使用以下代码将图像创建为按钮来拖动图像:(如该问题的答案所示: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];

And later I define:

后来我定义:

- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event
{
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view];
    UIControl *control = sender;
    control.center = point;
}

How can I make it return to it's original position after releasing it ?, for starters I will save the position at which each image is supposed to return, but then, there is anyway to indicate an UIImage to go from it's current position and move to another one ?, or any other alterative solution ?

我怎样才能让它在释放后回到原来的位置?,对于初学者来说,我会保存每个图像应该返回的位置,但是,无论如何,有一个 UIImage 从它的当前位置转到它的当前位置并移动到另一个?,或任何其他替代解决方案?

采纳答案by Hwee-Boon Yar

You know what, I was just working on this yesterday, so here you go with a little bonus animation:

你知道吗,我昨天刚刚在做这个,所以给你一些额外的动画:

- (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);
}

It still has a few magic numbers and I haven't renamed the functions and variables to suit your example, but it should be clear. I also did the indentation here since I don't manually break long lines in my code.

它仍然有一些神奇的数字,我没有重命名函数和变量以适合您的示例,但应该很清楚。我也在这里做了缩进,因为我没有在我的代码中手动打断长行。

回答by Tommy

UIGestureRecognizer is recommended by Apple for recent iOSes. You can use it not only for UIButton, but also for UIView (especially UIImageView in your case), etc. So I would like to recommend it.

UIGestureRecognizer 被 Apple 推荐用于最近的 iOS。您不仅可以将它用于 UIButton,还可以用于 UIView(尤其是您的情况下的 UIImageView)等。所以我想推荐它。

In the interface:

在界面中:

@interface TestDragViewController : UIViewController {
    IBOutlet UIImageView *dragImage;
    CGPoint originalCenter;
}

In viewDidLoad, plz remember to enable userInteraction:

在 viewDidLoad 中,请记住启用 userInteraction:

- (void)viewDidLoad {
    [super viewDidLoad];


    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self 
                                                                                 action:@selector(dragGesture:)];
    [dragImage addGestureRecognizer:panGesture];
    [dragImage setUserInteractionEnabled:YES];
}

And in its selector, I just set animation to visualize the returning effect:

在它的选择器中,我只是设置动画来可视化返回效果:

#pragma mark -
#pragma mark UIPanGestureRecognizer selector
- (void) dragGesture:(UIPanGestureRecognizer *) panGesture{
    CGPoint translation = [panGesture translationInView:self.view];

    switch (panGesture.state) {
        case UIGestureRecognizerStateBegan:{
            originalCenter = dragImage.center;
        }
            break;
        case UIGestureRecognizerStateChanged:{
            dragImage.center = CGPointMake(dragImage.center.x + translation.x,
                                           dragImage.center.y + translation.y);
        }
            break;
        case UIGestureRecognizerStateEnded:{            
            [UIView animateWithDuration:kImageReturnTime 
                             animations:^{
                                 dragImage.center = originalCenter;
                             }
                             completion:^(BOOL finished){
                                 NSLog(@"Returned");
                             }];
        }
            break;
        default:
            break;
    }

    [panGesture setTranslation:CGPointZero inView:self.view];
}

Cheers,

干杯,

Tommy

汤米

回答by Steve

Define CGPoint Globally, or in .h file.

全局定义 CGPoint,或在 .h 文件中。

  CGPoint point;          

      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];

And later I define:

后来我定义:

- (IBAction) imageMoved:(UIButton*) sender withEvent:(UIEvent *) event
 {
point = [[[event allTouches] anyObject] locationInView:self.view];
UIControl *control = sender;
control.center = point;
 [sender addTarget:self action:@selector(touches:withEvent:) forControlEvents:UIControlEventTouchUpInside];
}

-(void)touches:(UIButton *)button withEvent:(UIEvent *)event {

[UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionAllowUserInteraction animations:^{
     button.center = point;

 } completion:^(BOOL finished){
     if (finished) {
    // do anything yu want
   }

it works awesome cause i am using it in my project!

它工作得很棒,因为我在我的项目中使用它!

回答by Hetal Vora

How about calling a selector on UIControlEventTouchUpInside and then in the selector, just set the frame of your button to a new x and y coordinate (the ones that you have saved).

如何在 UIControlEventTouchUpInside 上调用选择器,然后在选择器中,只需将按钮的框架设置为新的 x 和 y 坐标(您已保存的坐标)。

回答by jeyben

In the solution I linked to in the thread you are referring I have created a generic drag drop manager that takes care of the return of a dragged object to the original position (if released outside a known dropzone). Currently there is no animation in the solution, but you could combine some of the ideas presented above.

在我在您所指的线程中链接到的解决方案中,我创建了一个通用的拖放管理器,负责将拖动的对象返回到原始位置(如果在已知拖放区之外释放)。目前解决方案中没有动画,但您可以结合上面介绍的一些想法。

See the some how generic drag and drop solution in iOS

查看iOS 中的一些通用拖放解决方案