I have properly set up UIDynamicBehavior
and UICollisionBehavior
however, none of my collisions are getting recognized as a hit in the delegate. I don't want to use UIGravityBehavior
to handle my "falling" animations so I used UIView.animate
instead but none of the delegate methods are getting hit.
class Test: UIViewController {
let collision = UICollisionBehavior()
let animator: UIDynamicAnimator?
override func viewDidLoad() {
/// view logic here
animator = UIDynamicAnimator(referenceView: view)
animator?.addBehavior(boundaryCollisionBehavior)
boundaryCollisionBehavior.collisionDelegate = self
boundaryCollisionBehavior.collisionMode = .boundaries
setupViews()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
boundaryCollisionBehavior.addBoundary(
withIdentifier: "shelf" as NSCopying,
from: CGPoint(x: 0, y: 200),
to: CGPoint(x: self.view.frame.width, y: 200)
)
}
func setupViews() {
let viewsForCollision: [UIView] = [view1, view2, view3]
UIView.animate(withDuration: animationTime, delay: 0, options: [.curveLinear], animations: {
viewsForCollision.forEach { $0?.transform = .identity }
})
viewsForCollision.compactMap { $0 }.forEach(boundaryCollisionBehavior.addItem)
}
}
extension Test: UICollisionBehaviorDelegate {
func collisionBehavior(
_ behavior: UICollisionBehavior,
endedContactFor item: UIDynamicItem,
withBoundaryIdentifier identifier: NSCopying?
) {
guard let boundary = identifier as? String else {
return
}
if boundary == "shelf" {
// Do something
}
}
}