将UIImages拖动到所选区域

时间:2012-11-15 11:17:51

标签: objective-c ios xcode uigesturerecognizer uipangesturerecognizer

新手obj-c问题。

我的任务是为iPad进行视觉呈现测试。在视图中我有三个UIImages(带有测试问题答案的图像)将被拖到区域进行回答的内容。如果选择了正确的图像,那么它需要留在这个区域,如果没有 - 它会回到起始位置。如果用户停止拖动而不是在区域中进行回答,则还需要返回到开始位置。 我试图实现这个:http://www.cocoacontrols.com/platforms/ios/controls/tkdragview但这对我来说太难了,因为我是一个超级新手。

我通过PanRecognizer实现了简单的图像拖动,因此拖动了三个图像中的每一个

 -(IBAction)controlPan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x, recognizer.view.center.y + translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
}

如果我以正确的方式思考,我需要设置CGPoint的开始和目标坐标,然后自定义Pan Gestures方法?如果不对,我可以用这种方式做到这一点?

1 个答案:

答案 0 :(得分:2)

你可以考虑这三种方法,也许这些对你来说更容易:

– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:

– touchesBegan:withEvent:的详细演示是:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    UITouch *touched = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touched.view];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    UITouch *touched = [[event allTouches] anyObject];
    // Here I suppose self.imageView contains the image user is dragging.
    CGPoint location = [touch locationInView:touched.view];
    // Here the check condition is the image user dragging is absolutely in the answer area.
    if (CGRectContainsRect(self.answerArea.frame, self.imageView.frame)) {
        // set transition to another UIViewController
    } else {
        self.imageView.center = location;    // Here I suppose you just move the image with user's finger.
    }
}

以下是Apple UIResponder Class Reference

的文档