触摸移动图像

时间:2012-10-29 10:00:58

标签: iphone objective-c ios uiscrollview uitouch

我有一个滚动视图,其中添加了固定数量的缩略图作为子视图。我想将这些图像沿着触摸移动到另一个视图中的矩形。我能够沿着滚动视图移动图像(即,沿着相同的视图)但不能移动到另一个视图。 现在正在根据触摸位置改变图像中心。当触摸点增加超出scrollview框架时,图像消失。这是我的问题

 - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [[event allTouches] anyObject];

        CGPoint location = [touch locationInView: self];
        NSLog(@"%f,%f",location.x,location.y);
        touch.view.center = location;

    }

这个问题的任何解决方案对我都有很大的帮助!!!

请参阅图片了解更多详情 enter image description here

1 个答案:

答案 0 :(得分:1)

这是我要做的:

为每个图像添加panGestureRecognizer,并使用以下handlePan:方法作为其操作。你仍然需要弄清楚如何获得正确的imageView(myImageView),但这将使你的图像跟随你的手指。

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

    // Find the correct image you're dragging
    // UIImageView *myImageview = ...

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

    if (recognizer.state == UIGestureRecognizerStateEnded) {
        // What to do when you start the gesture
        // You may also define myImageView here
        // (if so, make sure you put it in @interface,
        // because this method will be called multiple times,
        // but you will enter this "if" only when you start the touch)
    }

    // Keep your image in the screen
    if (myImageView.frame.origin.x + translation.x >= 0.0f &&
        myImageView.frame.origin.x + myImageView.frame.size.width + translation.x <= 320.0f &&
        myImageView.frame.origin.y + translation.y >= 0.0f &&
        myImageView.frame.origin.y + myImageView.frame.size.height + translation.y <= 480.0f) {

        myImageView.center = CGPointMake(myImageView.center.x + translation.x, 
                                         myImageView.center.y + translation.y);

    }

    if (recognizer.state == UIGestureRecognizerStateEnded) {
        // What to do when you remove your finger from the screen
    }

    [recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}