You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UICollisionBehaviorDelegate方法未调用问题求助

问题分析与解决方案

你的问题核心在于Swift 4及以后版本的Objective-C协议方法暴露规则:当你在Swift的extension中实现Objective-C定义的协议(比如UICollisionBehaviorDelegate)时,必须显式添加@objc修饰符,否则这些方法不会被Objective-C运行时识别,自然无法被调用。

具体修复步骤

给你的UICollisionBehaviorDelegate扩展中的所有方法添加@objc修饰符,修改后的代码如下:

extension ViewController: UICollisionBehaviorDelegate {
    // 添加@objc让Objective-C运行时能识别这些方法
    @objc func collisionBehavior(_ behavior: UICollisionBehavior, beganContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, at p: CGPoint) {
        print("began contact boundary")
    }

    @objc func collisionBehavior(_ behavior: UICollisionBehavior, endedContactFor item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?) {
        print("contact boundary ended")
    }

    @objc func collisionBehavior(_ behavior: UICollisionBehavior, endedContactFor item1: UIDynamicItem, with item2: UIDynamicItem) {
        print("contact item ended")
    }

    @objc func collisionBehavior(_ behavior: UICollisionBehavior, beganContactFor item1: UIDynamicItem, with item2: UIDynamicItem, at p: CGPoint) {
        print("began contact item")
    }
}

额外验证点

除了上述修复,我还检查了你代码中的其他部分:

  • UIDynamicAnimator的referenceView设置正确(使用physicsView作为容器,小球也添加到该视图中)
  • UICollisionBehavior的collisionMode设为.everything,包含了边界和item碰撞,符合需求
  • physicsView.isUserInteractionEnabled = false不会影响UIKitDynamics的运行(该框架不需要用户交互驱动物理效果)

修复后运行你的示例项目,就能看到控制台打印出碰撞相关的日志了。

内容的提问来源于stack exchange,提问作者user610246

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:33:15