Created
April 1, 2018 23:21
-
-
Save raulriera/2b752181585a26d8ea26f758e47986d9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
class ViewController: UIViewController { | |
@IBOutlet private weak var cardView: UIView! | |
private var animator: UIDynamicAnimator! | |
private var snapping: UISnapBehavior! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
animator = UIDynamicAnimator(referenceView: view) | |
snapping = UISnapBehavior(item: cardView, snapTo: view.center) | |
animator.addBehavior(snapping) | |
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(pannedView)) | |
cardView.addGestureRecognizer(panGesture) | |
cardView.isUserInteractionEnabled = true | |
} | |
@objc func pannedView(recognizer: UIPanGestureRecognizer) { | |
switch recognizer.state { | |
case .began: | |
animator.removeBehavior(snapping) | |
case .changed: | |
let translation = recognizer.translation(in: view) | |
cardView.center = CGPoint(x: cardView.center.x + translation.x, | |
y: cardView.center.y + translation.y) | |
recognizer.setTranslation(.zero, in: view) | |
case .ended, .cancelled, .failed: | |
animator.addBehavior(snapping) | |
case .possible: | |
break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment