将触摸转移到UIImageView的副本

时间:2011-06-30 11:20:33

标签: ios drag-and-drop uiimageview

我一直在尝试将UIImageViews从UITableView拖放到另一个视图。

我让一切都发挥作用。我将UIPanGestureRecognizer子类化并将此自定义识别器附加到我加载到表视图中的所有UIImageViews。

然后我覆盖识别器的touchesMoved方法,除其他外,在应用程序键窗口中添加一个临时视图,然后将所选UIImageView的副本添加到此临时视图中,如下所示:

UIView *dragAndDropView = [[UIView alloc] initWithFrame: [[UIScreen mainScreen] applicationFrame]];
        dragAndDropView.backgroundColor = [UIColor whiteColor];

        [[UIApplication sharedApplication].keyWindow addSubview: dragAndDropView]; 

        ElementImageView * sourceImageView = (ElementImageView*)self.view;

        ElementImageView *newImageView =  [[ElementImageView alloc] initWithImage:sourceImageView.image];
        newImageView.userInteractionEnabled = YES;
        newImageView.frame = [self.view convertRect:sourceImageView.frame toView:dragAndDropView];

        [dragAndDropView addSubview:newImageView];

作为这段代码的结果,我确实在我的dragAndDropView上获得了源图像视图的副本(我可以说,因为我将dragAndDropView的backgroundcolor设置为白色)。如果我抬起手指再次触摸复制的图像视图,我当然可以按照我的意愿将其拖动到屏幕上。但我无法找到将现有触摸无缝转移到新对象的方法。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我认为您可以在UIPanGestureRecognizer处理程序上执行以下操作:

-(void) handlePan:(UIPanGestureRecognizer *)recognizer  {

if (recognizer.state == UIGestureRecognizerStateBegan) {

    // the initial position
    initialPanPositionX = self.transform.tx;
    initialPanPositionY = self.transform.ty;

    // create a copy of the imageview
    panImage = [[UIImageView alloc] initWithImage:imageView.image];
    panImage.frame = imageView.frame;

    [self.view addSubview:panImage];

}
else if (recognizer.state == UIGestureRecognizerStateChanged) {

    if (!startedMoving) {
        startedMoving = YES;

        [UIView beginAnimations:nil context:NULL]; {
            [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
            [UIView setAnimationDuration:0.2f];

            // an effect to increase a copy a little bit when start dragging
            CGAffineTransform zt = CGAffineTransformScale(CGAffineTransformIdentity, 1.2, 1.2);

            panImage.bounds = CGRectApplyAffineTransform(panImage.bounds, zt);

        }
        [UIView commitAnimations];

    }

    // translation
    CGPoint point = [recognizer translationInView:self];
    panImage.transform = CGAffineTransformMakeTranslation(initialPanPositionX + point.x, initialPanPositionY + point.y);


}
else if (recognizer.state == UIGestureRecognizerStateEnded ) {

    startedMoving = NO;

    // drop the imageView if it's inside the droppable view


    [panImage release], panImage = nil;

}

}

希望它有所帮助。