3

我使用 UIPanGesture 在 iPhone 屏幕上移动图像。有些图像很小,当您在手指周围移动它们时,会遮挡您对图像本身的看法。我想在移动图像的同时设置图像的中心,以便图像中心实际上是触摸位置前面的 10 个点,而不是将其设置为触摸位置。

我测试了下面,但很快意识到它反复从 Y 中减去 10,使图像离触摸位置越来越远,最终离开屏幕,而不是保持恒定的 10 点偏移。

我应该怎么做?

- (void) TestGestureMethod:(UIPanGestureRecognizer *) panGesture {
    CGPoint translation = [panGesture translationInView:self.view];
    switch (panGesture.state) {
    case UIGestureRecognizerStateBegan:
        [self.view bringSubviewToFront:testObject];
        break;
    case UIGestureRecognizerStateChanged:
        testObject.center = CGPointMake(testObject.center.x + translation.x,
                                        testObject.center.y + translation.y);
        testObject.center = CGPointMake(testObject.center.x, testObject.center.y - 10);
        break;
    case UIGestureRecognizerStateEnded:
        break;
    }
    [panGesture setTranslation:CGPointZero inView:self.view];
}
4

3 回答 3

4

由于您不是在翻译图像而是手动设置其中心,您是否考虑过使用 UIGestureRecognizer locationInView: 而不是 translationInView:?

你可以做这样的事情......

- (void)TestGestureMethod:(UIPanGestureRecognizer *)panGesture
{
    CGPoint location = [panGesture locationInView:self.view];

    switch (panGesture.state) {
        ...
        case UIGestureRecognizerStateChanged:
            testObject.center = CGPointMake(location.x, location.y - 10);
        break;
        ... 
    }
}

这应该会导致图像中心始终位于触摸点下方 10 点处。

于 2013-01-19T07:47:06.737 回答
0

试试这个:

- (void) TestGestureMethod:(UIPanGestureRecognizer *) panGesture {
    CGPoint translation = [panGesture translationInView:self.view];
    switch (panGesture.state) {
    case UIGestureRecognizerStateBegan:
        [self.view bringSubviewToFront:testObject];
        testObject.center = CGPointMake(testObject.center.x, testObject.center.y - 10);
        break;
    case UIGestureRecognizerStateChanged:
        testObject.center = CGPointMake(testObject.center.x + translation.x,
                                        testObject.center.y + translation.y);

        break;
    case UIGestureRecognizerStateEnded:
        break;
    }
    [panGesture setTranslation:CGPointZero inView:self.view];
}
于 2013-01-19T07:43:02.603 回答
0

试试这个,这解决了你的问题:

- (void)handlePanGesture:(UIPanGestureRecognizer *)gestureRecognizer
{
    UIView *piece = [gestureRecognizer view];

    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gestureRecognizer translationInView:[piece superview]];

        [piece setCenter:CGPointMake([piece center].x + translation.x, [piece center].y + translation.y)];
        [gestureRecognizer setTranslation:CGPointZero inView:[piece superview]];
    }
}

我希望这会对你有所帮助。

于 2013-01-19T09:01:07.933 回答