I have a UIView and I want to move it only vertically by dragging it.

I used this code:

-(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);

}

If I do this, the view jumps up and down very quickly.

What am I doing wrong?

有帮助吗?

解决方案

This is possibly an issue with the coordinate systems and the view that is responding to the touch. When you get your location, it is in the coordinate system of touch.view, which could be your AddView. When you change the frame of AddView, the position of the touch will change as well, causing the "jumping" you are seeing.

You can make sure the location of the touch is given in coordinates of AddView's parent view with the line:

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

Also just a tip about Objective-C convention: instance variable names should generally start with a lowercase character and be accessed with dot notation: self.addView rather than AddView.

其他提示

Why not use a gesture recognizer?

It's a much simpler implementation.

Simply add a UIPanGestureRecognizer to the AddView:

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

[AddView addGestureRecognizer:panRecognizer];

And then handle the move:

-(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];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top