触摸事件发生时UIImageView跳转

时间:2013-10-12 04:22:19

标签: ios objective-c uiimageview touchesmoved

好的,基本上这段代码的作用是根据用户拖动它的位置沿Y轴上下拖动图像,然后返回原来的位置。我的问题是,如果有人不直接触摸UIImageView的中心并开始拖动它会摇晃(非常不平滑)。无论有人触摸UIImageView并开始拖动UIImageView稍微颠簸直接触摸事件的中心。

我在考虑使用动画来移动图像需要去的地方,还是有另一种方式?

如果这是一种效率低下的方法,我道歉。我对IOS世界还很陌生。

这就是我所拥有的:

-(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;
    }];
}

1 个答案:

答案 0 :(得分:1)

您还需要相对于父视图保存touchesBegan中的第一个位置。然后,您可以使用它来更改先前位置和新位置之间的差异。请参阅以下代码。

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