0

当设备被锁定时,我正在创建一个可拖动的 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);

    }
}

有什么想法吗?

4

1 回答 1

0

我最终使用了 UISlider。

我找到了下面的帖子,如果您正在寻找相同的解决方案,这将非常有帮助。

它有一个 xcode 项目的链接,该项目相当准确地再现了 Apple 的原生“滑动解锁”滑块功能。

http://www.iphonedevsdk.com/forum/iphone-sdk-development/11470-there-way-i-can-use-slide-unlock-slider.html#post124686

于 2010-02-22T17:38:50.937 回答