源碼地址:https://github.com/thermogl/TISpringLoadedViews,
這個比較複雜,我寫了個簡化版的:
https://www.dropbox.com/s/sv3yhm8dovh0adq/SpringDemo.zip
- ()simulateSpringWithDisplayLink:(CADisplayLink * (springEnabled && != CGPointMake(self.center.x -- CGPoint kx = CGPointMake(springConstant * displacement.x, springConstant * CGPoint bv = CGPointMake(dampingCoefficient * velocity.x, dampingCoefficient * CGPoint acceleration = CGPointMake((kx.x + bv.x) / mass, (kx.y + bv.y) /-= (acceleration.x *-= (acceleration.y * CGPoint newCenter =+= (velocity.x *+= (velocity.y *
這個方法由CADisplayLink負責調用,每秒鐘預設60次。要看懂這段代碼,首先你要瞭解彈簧的原理,比如拉起彈簧收到的力怎麼計算,往回彈收到的阻力怎麼計算。
下面是手勢操作的代碼,也就是拖動時觸發的方法:
- ()viewWasPanned:(UIPanGestureRecognizer *== CGPointMake(self.center.x + translation.x, self.center.y + (translation.x > && (translatedCenter.x - restCenter.x) >-= (translatedCenter.x - restCenter.x) - (translation.x < && (restCenter.x - translatedCenter.x) >+= (restCenter.x - translatedCenter.x) - (translation.y > && (translatedCenter.y - restCenter.y) >-= (translatedCenter.y - restCenter.y) - (translation.y < && (restCenter.y - translatedCenter.y) >+= (restCenter.y - translatedCenter.y) -+ translation.x, self.center.y +