我已经正确设置了
UIDynamicBehavior
和 UICollisionBehavior
但是,我的碰撞都没有被识别为委托中的命中。我不想使用 UIGravityBehavior
来处理我的“下降”动画,所以我使用了 UIView.animate
但没有一个委托方法被击中。
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
}
}
}