Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move UIView with relation to touch

i'm trying to move a UIView with relation to the user's touches.

Here's what I have at the moment:

int oldX, oldY;
BOOL dragging;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(window.frame, touchLocation)) {
        dragging = YES;
        oldX = touchLocation.x;
        oldY = touchLocation.y;
    }

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(window.frame, touchLocation) && dragging) {
        CGRect frame;
        frame.origin.x = (window.frame.origin.x + touchLocation.x - oldX);
        frame.origin.y = (window.frame.origin.y + touchLocation.y - oldY);
        window.frame = frame;

    }

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    dragging = NO;
}

The view keeps flickering from one location to another, and I don't know what else to do.

Any help appreciated.

like image 603
Jack Greenhill Avatar asked Dec 20 '10 10:12

Jack Greenhill


1 Answers

What you want is to use a UIPanGestureRecognizer, introduced in iOS 3.2. You use it with something as easy as this (from your UIViewController subclass):

-(void)viewDidLoad;
{
   [super viewDidLoad];
   UIPanGestureRecognizer* pgr = [[UIPanGestureRecognizer alloc] 
                                       initWithTarget:self
                                               action:@selector(handlePan:)];
   [self.panningView addGestureRecognizer:pgr];
   [pgr release];
}

-(void)handlePan:(UIPanGestureRecognizer*)pgr;
{
   if (pgr.state == UIGestureRecognizerStateChanged) {
      CGPoint center = pgr.view.center;
      CGPoint translation = [pgr translationInView:pgr.view];
      center = CGPointMake(center.x + translation.x, 
                           center.y + translation.y);
      pgr.view.center = center;
      [pgr setTranslation:CGPointZero inView:pgr.view];
   }
}
like image 192
PeyloW Avatar answered Sep 21 '22 09:09

PeyloW