iOS:在视图中平移

时间:2012-02-08 01:10:56

标签: ios cocoa-touch uigesturerecognizer pan

我设置了以下UIPanGestureRecognizer

- (void)pan:(UIPanGestureRecognizer *)gesture {
    if ((gesture.state == UIGestureRecognizerStateChanged) ||
        (gesture.state == UIGestureRecognizerStateEnded)) {
        CGPoint translation = [gesture translationInView:self.superview];
        gesture.view.center = CGPointMake(gesture.view.center.x + translation.x, gesture.view.center.y + translation.y);
        [gesture setTranslation:CGPointZero inView:self.superview];
    }
}

我想在视图中平移,在同一视图中将一个地方移动到另一个地方。这样做是在移动视图,我如何修改它以做我想做的事?

更新:这是我的方法最终正确平移的方式

- (void)pan:(UIPanGestureRecognizer *)gesture {
    if ((gesture.state == UIGestureRecognizerStateChanged) ||
        (gesture.state == UIGestureRecognizerStateEnded)) {
        CGPoint translation = [gesture translationInView:self];;
        self.origin = CGPointMake(self.origin.x + translation.x, self.origin.y + translation.y);
        [gesture setTranslation:CGPointZero inView:self];
    } 
}

origin是我视图中的一个属性,它只标记图形中心的位置。在其setter方法中,只要更改此值,就会有setNeedsDisplay更新

1 个答案:

答案 0 :(得分:6)

好吧,如果你想在不使用UIScrollView的情况下水平滚动,那么(这只是我的头顶,未经测试),试试这个:

- (void)pan:(UIPanGestureRecognizer *)gesture {
    if ((gesture.state == UIGestureRecognizerStateChanged) ||
        (gesture.state == UIGestureRecognizerStateEnded)) {
        CGPoint translation = [gesture translationInView:self.superview];
        gesture.view.center = CGPointMake(gesture.view.center.x + translation.x, gesture.view.center.y);
        [gesture setTranslation:CGPointZero inView:self.superview];
    }
}

您所做的就是忽略+ translation.y

如果您想使用UIScrollView(我推荐),请参阅以下教程之一:Are there any good UIScrollView Tutorials on the net?