使用 UIDynamicBehavior 向 UIView Pan 添加惯性
Adding Inertia to a UIView Pan with UIDynamicBehavior
我正在尝试使用 UIPanGestureRecognizer 平移 'blockView'。当平移 'Ended' 时,希望 'blockView' 以惯性减速,就像 UIScrollView 将以惯性结束滚动。
override func viewDidLoad() {
super.viewDidLoad()
self.dynamicAnimator = UIDynamicAnimator(referenceView: self.view)
let collider = UICollisionBehavior(items: [self.magnifiedView!])
collider.collisionDelegate = self
collider.collisionMode = .Boundaries
collider.translatesReferenceBoundsIntoBoundary = true
self.dynamicAnimator.addBehavior(collider)
self.dynamicProperties = UIDynamicItemBehavior(items: [self.magnifiedView!])
//self.dynamicProperties.elasticity = 1.0
//self.dynamicProperties.friction = 0.0
self.dynamicProperties.allowsRotation = false
//self.dynamicProperties.resistance = 10.0
self.dynamicAnimator.addBehavior(self.dynamicProperties)
}
func panBlockView (panGesture: UIPanGestureRecognizer) {
switch panGesture {
case .Began:
self.blockViewLocation = (self.blockView.center)!
case .Changed:
let translation = panGesture.translationInView(self.view)
self.blockView.center = CGPointMake(self.blockViewLocation.x + translation.x, self.self.blockViewLocation.y + translation.y)
case .Ended, .Cancelled:
self.dynamicAnimator.addLinearVelocity(panGesture.velocityInView(self.view), forItem: self.blockView)
}
}
问题:
当我平移视图时,'blockView' 尝试捕捉到平移起源的原点。当平移'Ends'时,它会产生惯性,但它会从平移的原点开始(捕捉到平移原点后)。
注意:
上面的代码可以毫无问题地平移视图。
添加捕捉行为并使其捕捉解决了问题。
我正在尝试使用 UIPanGestureRecognizer 平移 'blockView'。当平移 'Ended' 时,希望 'blockView' 以惯性减速,就像 UIScrollView 将以惯性结束滚动。
override func viewDidLoad() {
super.viewDidLoad()
self.dynamicAnimator = UIDynamicAnimator(referenceView: self.view)
let collider = UICollisionBehavior(items: [self.magnifiedView!])
collider.collisionDelegate = self
collider.collisionMode = .Boundaries
collider.translatesReferenceBoundsIntoBoundary = true
self.dynamicAnimator.addBehavior(collider)
self.dynamicProperties = UIDynamicItemBehavior(items: [self.magnifiedView!])
//self.dynamicProperties.elasticity = 1.0
//self.dynamicProperties.friction = 0.0
self.dynamicProperties.allowsRotation = false
//self.dynamicProperties.resistance = 10.0
self.dynamicAnimator.addBehavior(self.dynamicProperties)
}
func panBlockView (panGesture: UIPanGestureRecognizer) {
switch panGesture {
case .Began:
self.blockViewLocation = (self.blockView.center)!
case .Changed:
let translation = panGesture.translationInView(self.view)
self.blockView.center = CGPointMake(self.blockViewLocation.x + translation.x, self.self.blockViewLocation.y + translation.y)
case .Ended, .Cancelled:
self.dynamicAnimator.addLinearVelocity(panGesture.velocityInView(self.view), forItem: self.blockView)
}
}
问题: 当我平移视图时,'blockView' 尝试捕捉到平移起源的原点。当平移'Ends'时,它会产生惯性,但它会从平移的原点开始(捕捉到平移原点后)。
注意: 上面的代码可以毫无问题地平移视图。
添加捕捉行为并使其捕捉解决了问题。