简体   繁体   中英

Adding Inertia to a UIView Pan with UIDynamicBehavior

I am trying to pan 'blockView' with UIPanGestureRecognizer. When the pan is 'Ended', want the 'blockView' to decelerate with inertia, just as a UIScrollView would end scrolling with inertia.

在此处输入图片说明

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

Issue: As I pan the view, 'blockView' tries to snap to the origin where the pan was originated from. When the pan 'Ends', it creates inertia, but it starts from the origin of the pan (after snapping to pan origin).

NOTE: Above code works without issues just to PAN THE VIEW.

添加一个捕捉行为并对其进行捕捉可解决此问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM