我开发了一个应用程序并使用 UIKitDynamics 实现了碰撞检测。
碰撞检测正在工作。但不知何故,没有调用 UICollisionBehaviorDelegate 方法。不显示警告或错误。
我创建了一个示例项目来演示该问题:
import UIKit
class ViewController: UIViewController {
private var dynamicAnimator: UIDynamicAnimator?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.initPhysics()
}
fileprivate var initalized = false
fileprivate func initPhysics() {
if initalized {
return
}
initalized = true
let physicsView = UIView(frame: view.bounds.insetBy(dx: 40, dy: 40))
physicsView.backgroundColor = UIColor.black
self.dynamicAnimator = UIDynamicAnimator(referenceView: physicsView)
physicsView.isUserInteractionEnabled = false
view.addSubview(physicsView)
//Create ball
let frame = CGRect(x: 0, y: 0, width: 40, height: 40)
let rect = UIView(frame: frame)
rect.backgroundColor = UIColor.red
physicsView.addSubview(rect)
let behavior = UIDynamicItemBehavior(items: [rect])
behavior.elasticity = 1.0
behavior.resistance = 0.0
behavior.friction = 0.0
behavior.allowsRotation = false
self.dynamicAnimator?.addBehavior(behavior)
//collision behavior setup
let collisionBehavior = UICollisionBehavior(items: [rect])
collisionBehavior.collisionDelegate = self
collisionBehavior.setTranslatesReferenceBoundsIntoBoundary(with: .zero)
collisionBehavior.collisionMode = .everything
self.dynamicAnimator?.addBehavior(collisionBehavior)
//Push ball
let pushBehavior = UIPushBehavior(items: [rect], mode: UIPushBehaviorMode.instantaneous)
pushBehavior.active = true
pushBehavior.pushDirection = CGVector(dx: 0.5, dy: 0.5)
self.dynamicAnimator?.addBehavior(pushBehavior)
}
}
extension ViewController: UICollisionBehaviorDelegate {
// DELEGATE METHODS NOT CALLED
func collisionBehavior(_ behavior: UICollisionBehavior,
beganContactFor item: UIDynamicItem,
withBoundaryIdentifier identifier: NSCopying?,
at p: CGPoint) {
print("began contact boundary")
}
func collisionBehavior(_ behavior: UICollisionBehavior,
endedContactFor item: UIDynamicItem,
withBoundaryIdentifier identifier: NSCopying?) {
print("contact boundary ended")
}
func collisionBehavior(_ behavior: UICollisionBehavior,
endedContactFor item1: UIDynamicItem,
with item2: UIDynamicItem) {
print("contact item ended")
}
func collisionBehavior(_ behavior: UICollisionBehavior,
beganContactFor item1: UIDynamicItem,
with item2: UIDynamicItem,
at p: CGPoint) {
print("began contact item")
}
}
基础 SDK:iOS 11.2,Xcode 版本 9.2 (9C40b)
谢谢您的帮助!