加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

iphone – 拖放对象并将其返回到原始位置

发布时间:2020-12-14 17:58:35 所属栏目:百科 来源:网络整理
导读:我试图拖动一个图像,让它在释放后返回原来的位置.到目前为止,我可以使用以下代码将图像创建为按钮来拖动图像:(如此问题的答案中所示: Basic Drag and Drop in iOS) UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];[button addTarget:sel
我试图拖动一个图像,让它在释放后返回原来的位置.到目前为止,我可以使用以下代码将图像创建为按钮来拖动图像:(如此问题的答案中所示: 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);
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读