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

模态展示ViewController在Tabbar上方触发NSInvalidArgumentException错误求助

解决模态展示时的"Application tried to present modally an active controller"错误(保持TabBar显示)

先理清楚你的场景:

tabbarcontroller -> 点击tabbaritem -> UIViewController -> 点击按钮 -> 模态展示ViewController

你当前的代码:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let VC1 = storyboard.instantiateViewController(withIdentifier: "MyControlerVC") as! MyControlerVC
self.definesPresentationContext = true
VC1.modalPresentationStyle = .overCurrentContext
self.present(VC1, animated: true, completion: nil)
// self.tabbarcontroller.present(VC1, animated: true, completion: nil)

遇到的错误:

NSInvalidArgumentException', reason: 'Application tried to present modally an active controller

问题根源分析

这个错误本质是你尝试去模态展示一个已经处于活跃状态(正在显示或已经被present)的控制器实例。另外,你想要保留TabBar显示的需求,也需要调整模态发起的主体和展示样式的搭配。

具体解决方案

1. 确保每次展示都是新的控制器实例

虽然你代码里每次都通过storyboard实例化VC1,但要排查有没有在其他地方持有这个实例的引用,导致重复调用present时用了同一个已经活跃的对象——这是触发错误的常见原因。

2. 调整模态发起者,确保TabBar保留显示

要让TabBar保持在下方显示,最佳方式是让TabBarController作为模态展示的发起者,而不是当前的子ViewController。修改后的代码如下:

// 先确保能获取到当前的TabBarController
guard let tabBarController = self.tabBarController else { return }

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let VC1 = storyboard.instantiateViewController(withIdentifier: "MyControlerVC") as! MyControlerVC

// overCurrentContext样式会让新VC覆盖在当前上下文之上,TabBar属于TabBarController的视图层级,会被保留显示
VC1.modalPresentationStyle = .overCurrentContext

// 让TabBarController发起present操作,避免子VC状态问题导致的错误
tabBarController.present(VC1, animated: true, completion: nil)

3. 额外检查项

  • 检查你的MyControlerVC在Storyboard里的模态样式设置,确保代码里的modalPresentationStyle能正常覆盖(如果Storyboard里设置了其他样式,可能会干扰)。
  • 排查按钮的点击事件是否被重复绑定,导致一次点击触发多次present调用,进而尝试展示已经活跃的控制器。
  • 绝对不要用单例模式来管理这个要模态展示的VC,每次展示都必须实例化新对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:03:12