0

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
        }
    }
}
swiftcode123
  • 105
  • 5
  • If you don't like `UIGravityBehavior`, how about creating your custom `UIDynamicBehaviour`? – Sweeper Mar 17 '23 at 01:48
  • @Sweeper I am confused on how to set up code like ` tests.compactMap { $0 }.forEach { token in let originalTransform = CGAffineTransform.identity token.transform = originalTransform.scaledBy(x: 0.4, y: 0.4) } UIView.animate(withDuration: animationTime, delay: 0, options: [.curveLinear], animations: { tests.forEach { $0?.transform = .identity } }) ` be a custom UIDynamicBehavior – swiftcode123 Mar 17 '23 at 16:29

0 Answers0