Search code examples
iosobjective-ccocoa-touchdrawrecttouchesmoved

Draggable UIView moves incorrectly


I'm using a UIView subclass to play a video within an AVPlayer. It works fine, and there are no problems. However, I would like this view to be draggable. Within its class, I have the touchesMoved delegate method that does the following:

CGPoint tap = [[touches anyObject] locationInView:self];
self.center = tap;

However, this is incredibly glitchy. The uiview, who's bounds are {{0, 0}, {342, 256}} moves from where my finger is to the top left of my screen really rapidly, and when I let go, it disappears. How can I make the point at which I tapped in the UIView move to where my finger is currently, and why does it move to the top left? Am I doing something wrong??


Solution

  • You should try do something like this:

    Remember the starting location in touchesBegan:

    UITouch *touch = [touches anyObject];
    self.startTouchPoint = [touch locationInView:self];         
    

    Move the view by the difference in position in touchesMoved :

        CGPoint movedPoint = [touch locationInView:self];
    
        CGFloat deltaX = movedPoint.x - _startTouchPoint.x;
        CGFloat deltaY = movedPoint.y - _startTouchPoint.y;
        CGPoint center = self.center;
        center.x += x;
        center.y += y;
        self.center = center;