I'm creating a draggable UIImageView much like the iPhone/iPod Touch's "Slide to Unlock" slider when the device is locked.
I can get the view to move smoothly along the x-axis by using: float newCenter = touchPoint.x;
But this doesn't take into account the offset of the touch from the center. It's simply moving the center point of the view to the touch point. I'm trying to move the view by dragging it from any point along the x-axis of the UIImageView.
Below, I tried calculating the newCenter within TouchesMoved but it fails to slide smoothly.
The code:
- (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);
}
}
Any thoughts?