2017-02-23 181 views
0

我發現這個代碼線上平移視圖時實現該橡膠帶效應:如何實現橡皮筋效果?

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

所得效果示於下面的GIF:

enter image description here

然而,我有麻煩理解代碼如何工作,並在我自己的項目中再現這種效果。例如,我不明白的一件事是,向上平移綠色視圖時yTransition將是負數,負數不會有對數(在logConstraintValueForYPoisition(:)方法中)。如果有人能夠向我解釋這段代碼如何一步一步地工作,我會非常感激。

The original post can be found here.

+0

你可以使用'UIView.animate(:usingSpringWithDamping)'也有彈簧動畫 – Tj3n

+0

@ Tj3n:他們確實使用它。日誌是爲了別的。 – Dair

+0

猜測日誌正在用於彈簧動畫所具有的最大位置 – Tj3n

回答

4

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來完成此操作。

請注意,如果你有一個正值x,log(x) < x