如何实现橡皮筋效应?

问题描述:

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

I found this code online that implements the rubber band effect when panning a view:

@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))
 }

产生的效果如下图所示:

The resulting effect is shown in the gif below:

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

However, I have trouble understanding how this code works, and reproducing this effect in my own projects. For instance, one of the things I do not understand is, when panning the green view upwards yTransition is going to be negative and negative numbers do not have logarithms (in the logConstraintValueForYPoisition(:) method). I would really appreciate it if someone could explain to me how this code works step by step.

可以在此处找到原始帖子.

log 不是您所想的.事实上,该片段是不完整的.可以在此处找到该存储库.

The log is not what you're thinking of. In fact, the snippet is incomplete. The repo can be found here.

弹跳动画在这里>

The bouncing animation is 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.

The log portion is for moving the green rectangle up. Once you reach an upward threshold (hasExceededVerticalLimit(topViewConstraint.constant)) you want the rectangle to stop moving as quick as you don't want it to keep up with your finger, you do this by calling logConstraintValueForYPoisition.

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

Note that if you have a positive value x, log(x) < x.