当设备被锁定时,我正在创建一个可拖动的 UIImageView,就像 iPhone/iPod Touch 的“滑动解锁”滑块一样。
我可以使用以下命令使视图沿 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);
}
}
有什么想法吗?