2013-10-12 41 views
0

好吧,基本上這個代碼目前所做的是沿着Y軸上下拖動圖像,這取決於用戶拖動它的位置,並且它返回到原來的位置。我的問題是,如果有人不直接觸及UIImageView的中心,並開始拖動它會震動(非常不流暢)。無論何人觸摸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

您還需要保存的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; 
    } 
} 
+0

非常感謝!現在我可以看到它。這正是我想要的。再次感謝你! – user2873147