Question

Okay basically what this code currently does is drag an image up and down along the Y axis depending on where the user drags it, and it returns to its original position. My problem is that if someone were to not touch directly on the center of the UIImageView and start dragging it would jolt (very not smooth). Wherever someone is touching the UIImageView and starts dragging the UIImageView jolts a little to go directly on the center of the touch event.

I was thinking about using animation just to move it where the image needs to go, or is there another way?

I apologize if this is an inefficient way to do this. I'm fairly new to the IOS world.

Here's what I have:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    //Gets location of UIImageView.
    self.originalFrame = self.foregroundImage.frame;
}
//This method is used for moving the UIImageView along the y axis depending on touch events.
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    if([touch view]==self.foregroundImage) {
        CGPoint location = [touch locationInView:self.view];
        location.x=self.foregroundImage.center.x;
        self.foregroundImage.center=location;
    }
}
//This method sets the UIImageView back to its original position.
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    CGRect newFrame = self.foregroundImage.frame;
    newFrame.origin.y = self.originalFrame.origin.y;
    [UIView animateWithDuration:1.1 animations:^{
        self.foregroundImage.frame = newFrame;
    }];
}
Was it helpful?

Solution

You also need to save the first location in touchesBegan, relative to the parent view. Then, you can use that to change the frame by the difference between the previous location and the new location. Please see the following code.

- (void) touchesBegan: (NSSet*)   touches
            withEvent: (UIEvent*) event
{
  if (touches.count == 1)
  {
    UITouch* touch = [touches anyObject];
    self.touchLocation = [touch locationInView: self.view];
  }
}

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

    if (touch.view == self.foregroundImage)
    {
      /* Determine the difference between the last touch locations */
      CGFloat deltaX = newTouchLocation.x - self.touchLocation.x;
      CGFloat deltaY = newTouchLocation.y - self.touchLocation.y;

      /* Offset the foreground image */
      self.foregroundImage.center
        = CGPointMake(self.foregroundImage.center.x + deltaX,
                      self.foregroundImage.center.y + deltaY);
    }

    /* Keep track of the new touch location */
    self.touchLocation = newTouchLocation;
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top