Question

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??

Was it helpful?

Solution 2

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;

OTHER TIPS

You're having a problem with frames of reference. When you ask for locationInView:self, you're asking for the touch in your subview's coordinate system. (i.e. the top-left corner of your view is (0, 0).) The center property of the subview, though, is in the superview's coordinate system (i.e. the top-left corner of the superview is (0, 0)). So, if you tap on the top-left corner of your subview, the locationInView:self you get back will be (0, 0) and setting that to be your subview's center will position it in the top left of the super view.

You probably want to get the locationInView:self.superview, so that the point you get back is in the superview's coordinate system. Or, even better, have the super view do the touch handling. (It's usually considered poor form to modify your own center; each view is typically designed to be agnostic about its superview and its position within it.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top