如何实现橡皮筋效果?

How to implement the rubber band effect?

我在网上找到了这段实现平移视图时的橡皮筋效果的代码:

@IBAction func viewDragged(sender: UIPanGestureRecognizer) {

  let yTranslation = sender.translationInView(view).y
    if (hasExceededVerticalLimit(topViewConstraint.constant)){
      totalTranslation += yTranslation
      topViewConstraint.constant = logConstraintValueForYPoisition(totalTranslation)
    if(sender.state == UIGestureRecognizerState.Ended ){
       animateViewBackToLimit()
    }
    } else {
      topViewConstraint.constant += yTranslation
    }
     sender.setTranslation(CGPointZero, inView: view)
 }

 func logConstraintValueForYPoisition(yPosition : CGFloat) -> CGFloat {
  return verticalLimit * (1 + log10(yPosition/verticalLimit))
 }

生成的效果如下图所示:

但是,我很难理解这段代码的工作原理,也很难在我自己的项目中重现这种效果。例如,我不明白的一件事是,当向上平移绿色视图时 yTransition 将是负数并且负数没有对数(在 logConstraintValueForYPoisition(:) 方法中)。如果有人能逐步向我解释这段代码是如何工作的,我将不胜感激。

The original post can be found here.

log 不是你想的那样。事实上,片段是不完整的。可以在 here.

找到回购协议

弹跳动画为here:

func animateViewBackToLimit() {
    self.topViewConstraint.constant = self.verticalLimit

    UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 10, options: UIViewAnimationOptions.AllowUserInteraction, animations: { () -> Void in
        self.view.layoutIfNeeded()
        self.totalTranslation = -200
        }, completion: nil)
}

log部分用于将绿色矩形向上移动。一旦达到向上阈值 (hasExceededVerticalLimit(topViewConstraint.constant)),您希望矩形停止移动的速度与您不希望它跟上手指的速度一样快,您可以通过调用 logConstraintValueForYPoisition.[=19 来实现=]

请注意,如果您有一个正值 xlog(x) < x