I'm doing a simple animation which requires me to handle some collisions with boundaries.
I have a class, viewcontroller, which I extend to be a UICollisionBehaviorDelegate so I can recognize and handle view collisions.
For some reason, when a collision happens, my delegate methods never fire.
class ViewController: UIViewController {
var fallingImageViews: [UIImageView]!
var downAnimator: UIDynamicAnimator!
override func viewDidLoad() {
super.viewDidLoad()
//imagine fallingImageViews Initializers happening here
downAnimator = initializeAnimators()
}
func initializeAnimators() -> UIDynamicAnimator {
let downwardAnimator = UIDynamicAnimator(referenceView: self.view)
downwardAnimator.addBehavior(setBoundaries())
downwardAnimator.addBehavior(setGravity())
downwardAnimator.addBehavior(setBounciness())
downwardAnimator.delegate = self
return downwardAnimator
}
func setBoundaries() -> UICollisionBehavior {
let boundaries = UICollisionBehavior(items: fallingImageViews)
boundaries.collisionDelegate = self
// prevent collisions between items
boundaries.collisionMode = .boundaries
boundaries.setTranslatesReferenceBoundsIntoBoundary = true
return boundaries
}
}
// MARK: Collision Behavior Delegate
extension ViewController: UICollisionBehaviorDelegate, UIDynamicAnimatorDelegate {
func collisionBehavior(_ behavior: UICollisionBehavior, endedContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?) {
print(identifier)
}
func collisionBehavior(_ behavior: UICollisionBehavior, beganContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, at p: CGPoint) {
print(identifier)
}
}
I completely scrapped my old answer and updated it. I'm sorry I mislead you, but here is my revised answer:
The idea is that you add behaviors to the objects you want animated (in your case, your
fallingImageViews
).So all the code here should actually go into a class that inherits from UIImageView (in my example code you'll see that I'm inheriting from a CardCtrl object, but it might as well be a UIImageView).
The only changes you have to make is your
UIDynamicAnimator
's reference view has to besuperview
and that all the the reference views for all your animation behaviors are set to[self]
.Here is some example code from one of my old projects: