0

I try to build tinder like interface and I want View to snap with bounces to center of parent view, when finger is released. I try to implement it with snap behavios and pan gesture recognizer, but insted I see animation of falling view down.

enter image description here

My code is following

class ViewController: UIViewController {

var d = UIView()
var snap: UISnapBehavior!
var animator:UIDynamicAnimator!

override func viewDidLoad() {
    super.viewDidLoad()

    d.translatesAutoresizingMaskIntoConstraints = false
    d.backgroundColor = .redColor()

    view.addSubview(d)

    d.heightAnchor.constraintEqualToConstant(150).active = true
    d.widthAnchor.constraintEqualToConstant(150).active = true
    d.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
    d.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor).active = true

    d.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "pan:"))

    animator = UIDynamicAnimator(referenceView: d)


}

func pan(gesture:UIPanGestureRecognizer) {
    switch gesture.state {
    case .Changed:
        d.frame.origin.x = gesture.translationInView(d).x
    case .Ended:
        snap = UISnapBehavior(item: d, snapToPoint: view.center)
        animator.addBehavior(snap)
    default:
        break
    }
}
}
Alexey K
  • 6,537
  • 18
  • 60
  • 118

1 Answers1

0

You should setup the referenceView of the UIDynamicAnimator to view and not d.

animator = UIDynamicAnimator(referenceView: view)

Here is the code I normally use for my pan gesture. It also tilts the block while panning:

func pan(gesture:UIPanGestureRecognizer) {

    let panLocationInView = gesture.locationInView(view)
    let panLocationInD = gesture.locationInView(d)

    switch gesture.state {
    case .Began:
        animator.removeAllBehaviors()
        let offset = UIOffsetMake(panLocationInD.x - CGRectGetMidX(d.bounds), panLocationInD.y - CGRectGetMidY(d.bounds))
        attachmentBehaviour = UIAttachmentBehavior(item: d, offsetFromCenter: offset, attachedToAnchor: panLocationInView)
        animator.addBehavior(attachmentBehaviour!)
    case .Changed:
         attachmentBehaviour?.anchorPoint = panLocationInView
    case .Ended:
        animator.removeAllBehaviors()
        animator.addBehavior(UISnapBehavior(item: d, snapToPoint: view.center))
    default:
        break
    }

}

enter image description here

Carien van Zyl
  • 2,853
  • 22
  • 30