在我的iPad应用程序中拖放

时间:2012-05-05 22:03:31

标签: cocoa-touch drag-and-drop uikit uiimageview

我已经从另一位绅士那里调整了这个代码。它到目前为止工作得很好,但在我的应用程序中,我计划有相当多的图像视图/按钮移动。实现这个的最佳方法是什么?也许将对象放入数组并使用枚举器?如果其他人做了类似的事情,那么在正确的方向上轻推将非常感激! 顺便说一下,他们在视图中都会有不同的坐标

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragGesture:)];

[dragImage addGestureRecognizer:panGesture];
[dragImage setUserInteractionEnabled:YES];
}

#pragma mark -
#pragma mark UIPanGestureRecognizer selector
- (void) dragGesture:(UIPanGestureRecognizer *) panGesture{


CGPoint translation = [panGesture translationInView:self.view];

switch (panGesture.state) {
    case UIGestureRecognizerStateBegan:{
        originalCentre = dragImage.center;
    }
        break;
    case UIGestureRecognizerStateChanged:{
        dragImage.center = CGPointMake(dragImage.center.x + translation.x,
                                       dragImage.center.y + translation.y);
    }
        break;
    case UIGestureRecognizerStateEnded:{            
        if (((dragImage.center.x >= 280) && (dragImage.center.y >= 280) &&
            (dragImage.center.x <= 450) && (dragImage.center.y <= 450))) {

            dragImage.center = CGPointMake(300, 300);
            [dragImage setUserInteractionEnabled:NO];
            break;
        }
        [UIView animateWithDuration:0.5 
                         animations:^{
                             dragImage.center = originalCentre;
                         }
                         completion:^(BOOL finished){
                         }];
    }
        break;
    default:
        break;
}

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

-(IBAction)clear{
[UIImageView animateWithDuration:0.5 animations:^{
dragImage.center = CGPointMake(100, 200);
}];

[dragImage setUserInteractionEnabled:YES];
}

非常感谢您花时间阅读这个问题。

1 个答案:

答案 0 :(得分:2)

您可以使用recognizer.view来确定要移动的视图。不要总是更改drawImage,只需使用recognizer.view即可。当识别器开始时,请确保将其取消(将enabled设置为NO然后YES),如果它是想要成为的子视图拖投掷的。

您可能需要更改其中一些幻数,具体取决于要移动的视图。