我正在做一个简单的动画,它需要我处理一些与边界的碰撞。
我有一个类 viewcontroller,我将其扩展为 UICollisionBehaviorDelegate,这样我就可以识别和处理视图冲突。
出于某种原因,当发生碰撞时,我的委托方法永远不会触发。
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)
}
}