移动UIView Probleme

时间:2013-11-05 18:49:02

标签: ios objective-c position drag touchmove

我有一个UIView,我想通过拖动它来垂直移动它。

我使用了这段代码:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];

AddView.frame = CGRectMake(AddView.frame.origin.x, location.y, AddView.frame.size.width, AddView.frame.size.height);

}

如果我这样做,视图会很快上下跳动。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

这可能是坐标系和响应触摸的视图的问题。当您获得位置时,它位于touch.view的坐标系中,可以是您的AddView。当你改变AddView的框架时,触摸的位置也会改变,导致你看到的“跳跃”。

您可以确保触摸的位置以AddView的父视图的坐标给出,并带有以下行:

CGPoint location = [touch locationInView:AddView.superview];

还有一个关于Objective-C约定的提示:实例变量名称通常应以小写字符开头,并使用点表示法访问:self.addView而不是AddView

答案 1 :(得分:0)

为什么不使用手势识别器?

这是一个更简单的实现。

只需将UIPanGestureRecognizer添加到AddView:

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];

[AddView addGestureRecognizer:panRecognizer];

然后处理此举:

-(void)move:(UIPanGestureRecognizer*)recognizer {
    CGPoint translatedPoint = [recognizer translationInView:self.view];

    if([(UIPanGestureRecognizer*) recognizer state] == UIGestureRecognizerStateBegan) {
        _firstY = recognizer.view.center.y;
    }

    translatedPoint = CGPointMake(recognizer.view.center.x, _firstY+translatedPoint.y);

    [recognizer.view setCenter:translatedPoint];
}