2010-02-22 55 views
0

我創建了一個可拖動的UIImageView,與iPhone/iPod Touch的「Slide to設備鎖定時解鎖「滑塊。在1軸上拖動UIImageView/UIView而不讓view.center跳轉到觸摸位置(從視圖上的任意位置拖動到在x軸上移動)

我可以通過以下方式使視圖沿着X軸平滑移動:float newCenter = touchPoint.x;

但是這並沒有考慮到觸摸與中心的偏移。它只是將視圖的中心點移動到觸摸點。我試圖通過從UIImageView的x軸上的任何點拖動視圖來移動視圖。

下面,我試着計算TouchesMoved內的newCenter,但它無法順利滑動。

代碼:

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

    UITouch *touch = [touches anyObject]; 
    CGPoint touchPoint = [touch locationInView:self]; // self is a UIView 

    CGRect sliderRect = sliderView.frame; // sliderView is a UIImageView 

    if (CGRectContainsPoint(sliderRect, touchPoint)){ 

     float sliderHalfWidth = sliderView.frame.size.width/2; 
     float leftEdge = sliderView.center.x - sliderHalfWidth; 
     float distanceToTouchFromEdge = touchPoint.x - leftEdge; 

     float newCenter = (distanceToTouchFromEdge - sliderHalfWidth) + touchPoint.x; // <--- the math here is probably incorrect. I tried a few other formulas, none of which gave me the results I was looking for. 
     //float newCenter = touchPoint.x; <--- This slides smoothly but always centers view on touch-point (we want to drag from anywhere) 

     NSLog(@"--------------"); 
     NSLog(@"sliderHalfWidth: %f", sliderHalfWidth); 
     NSLog(@"sliderView.center.x: %f", sliderView.center.x); 
     NSLog(@"leftEdge: %f", leftEdge); 
     NSLog(@"distanceToTouchFromEdge: %f", distanceToTouchFromEdge); 
     NSLog(@"touchPoint.x: %f", touchPoint.x); 
     NSLog(@"newCenter: %f", newCenter); 
     NSLog(@"--------------"); 

     sliderView.center = CGPointMake(newCenter, sliderView.frame.size.height/2); 

    } 
} 

有什麼想法?

回答