用动量实现按钮拖动?

时间:2014-11-19 15:00:15

标签: ios objective-c cocoa-touch

我已经设法使用此链接中显示的代码在Objective-C中为iPhone应用程序实现了一个可拖动按钮: http://www.cocoanetics.com/2010/11/draggable-buttons-labels/

我想知道是否存在一个可以实现拖动动力的库? 因此,如果用户移动按钮然后松开,它将继续移动一段时间,具体取决于阻力系数。

我搜索了一个图书馆,用Google搜索"带有动量的按钮#34;但是空了......

2 个答案:

答案 0 :(得分:3)

如果您必须支持iOS 6

当平移手势结束时,您可以动画更改按钮的center

if(panGestureRecognizer.state == UIGestureRecognizerStatedEnded)
{
    finalVelocty.x = velocity.x;
    finalyVelocity.y = velocity.y;
    NSTimeInterval animationTime = 0.25; //adjust the time to your needs
    [UIView animateWithDuration:0.25 animations:^{
      button.center = ... // calculate button's 'final' center (depending on velocity?)
    } completion:nil]; 
}

适用于iOS 7或更高版本

Apple在iOS 7中引入了UIKit Dynamics框架(由UIDynamicAnimator和UIDynamicItemBehavior子类组成)。它是集成到UIKit中的物理引擎。您可以使用它来实现“动量”效果。

您可能会发现有用的示例:http://www.teehanlax.com/blog/introduction-to-uimotioneffect/

答案 1 :(得分:1)

我最终使用平移手势识别器为我的目的解决了这个问题。 在手势识别器方法中,我得到最终速度。

if(timeDiff > 0.2)
{
    velocity.x = velocity.y = 0;
}

if(panGestureRecognizer.state == UIGestureRecognizerStatedEnded)
{
    finalVelocity.x = velocity.x;
    finalVelocity.y = velocity.y;

    // Start a timer and implement the object movement in the timer callback
}

如果有人知道更好的方法,请告诉我:)