Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/93.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 移动视图问题_Ios_Objective C_Position_Drag_Touchmove - Fatal编程技术网

Ios 移动视图问题

Ios 移动视图问题,ios,objective-c,position,drag,touchmove,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.ori

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

}
如果我这样做,视图会快速上下跳跃


我做错了什么?

这可能是坐标系和对触摸做出响应的视图的问题。当您获取位置时,它位于
touch.view
的坐标系中,该坐标系可能是您的AddView。当您更改AddView的帧时,触摸的位置也将更改,从而导致您看到的“跳跃”

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

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

还有一个关于Objective-C约定的提示:实例变量名通常应该以小写字符开头,并使用点符号进行访问:
self.addView
,而不是
addView
,为什么不使用手势识别器呢

这是一个简单得多的实现

只需将UIPangestureRecognitor添加到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];
}

并添加动画以进行平滑移动查看:
[UIView animateWithDuration:0.2延迟:0选项:UIViewAnimationOption BeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction动画:^{view.frame=endAnimationFrame;}完成:nil];