ios - 如何实现橡皮筋效果?

标签 ios swift uigesturerecognizer

我在网上找到这段代码,实现了平移 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))
 }

生成的效果如下图所示:

enter image description here

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

The original post can be found here.

最佳答案

log不是你想的。事实上,片段是不完整的。可以找到 repo 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 来实现。 .

注意,如果你有一个正值x , log(x) < x .

关于ios - 如何实现橡皮筋效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42406064/

相关文章:

javascript - 如何在 UIWebView 中从 Javascript 调用 Objective-C 方法?

ios - plist writeToFile 覆盖整个plist

ios - 如何从 TableView 中删除特定数据

ios - (Swift2 SpriteKit) 如何有效地在 SKScene 和 UIViewController 之间转换?

ios - Swift中如何保持Dictionary中数据的顺序?

ios - 使用手势识别器和 swift 查找发件人标签

iphone - 如何在iphone中获取pinchgesture的坐标

iphone - ios 对象在 Debug 模式下会被释放,但在 Release 模式下不会被释放

ios - 创建 TableView ,其行为或外观类似于日期选择器

iphone - 如何使 UITableView 上的 SwipeGestureRecognizer 响应更快?