0

我有一个 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);

}

如果我这样做,视图会非常快速地上下跳跃。

我究竟做错了什么?

4

2 回答 2

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];
}
于 2013-11-05T22:43:31.180 回答
0

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

您可以确保触摸的位置在 AddView 的父视图的坐标中给出:

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

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

于 2013-11-05T19:11:41.643 回答