0

好的,基本上这段代码当前所做的就是根据用户拖动图像的位置沿 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;
    }];
}
4

1 回答 1

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;
  }
}
于 2013-10-12T06:41:01.887 回答