【问题标题】:Drag a UIImageView/UIView on 1 axis without having view.center jump to touch location (dragging from anywhere on view to move on x-axis)在 1 轴上拖动 UIImageView/UIView 而无需 view.center 跳转到触摸位置(从视图上的任何位置拖动以在 x 轴上移动)
【发布时间】:2010-02-22 08:15:36
【问题描述】:

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

    }
}

有什么想法吗?

【问题讨论】:

    标签: iphone objective-c cocoa-touch slider uislider


    【解决方案1】:

    我最终使用了 UISlider。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 2021-02-05
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      相关资源
      最近更新 更多