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

使用self.present调用VC时NavigationItem不显示,已困扰多日求帮助

解决Present的ViewController中NavigationItem不显示的问题

嘿,这个问题我之前也踩过坑!核心原因很明确:用present模态弹出的ViewController,默认并没有嵌入到UINavigationController中,而NavigationItem的所有配置(标题、自定义按钮等)都依赖UINavigationBar才能展示,直接present自然看不到导航项。

给你两种实用的解决方案,优先推荐第一种:

方案一:把ViewController包装进UINavigationController再present

这是最贴合iOS设计规范的做法,只需要修改你present的代码,原ViewController的customization方法完全不用改动:

// 假设你原来的present代码是这样的:
// let targetVC = YourTargetViewController()
// self.present(targetVC, animated: true)

// 修改为下面的写法,把目标VC包装进导航控制器
let targetVC = YourTargetViewController()
let navController = UINavigationController(rootViewController: targetVC)
self.present(navController, animated: true)

这样弹出后,导航栏会自动加载,你在customization里配置的标题、自定义返回按钮都会正常显示。

方案二:手动给ViewController添加导航栏(适合特殊场景)

如果你不想依赖UINavigationController,可以手动在目标VC的view上添加UINavigationBar,再绑定你的navigationItem:

func customization() {
    // 1. 创建并添加适配安全区域的导航栏
    let navBarHeight: CGFloat = 44
    let navBar = UINavigationBar(frame: CGRect(
        x: 0,
        y: view.safeAreaInsets.top,
        width: view.frame.width,
        height: navBarHeight
    ))
    view.addSubview(navBar)
    
    // 2. 将navigationItem绑定到导航栏
    navBar.items = [self.navigationItem]
    
    // 3. 继续你的原有配置
    self.navigationItem.title = self.currentUser?.displayName
    let icon = UIImage(named: "back")?.withRenderingMode(.alwaysTemplate)
    let backButton = UIBarButtonItem(image: icon!, style: .plain, target: self, action: #selector(dismissSelf))
    self.navigationItem.leftBarButtonItem = backButton
}

// 自定义返回按钮的点击事件,手动关闭模态页
@objc func dismissSelf() {
    self.dismiss(animated: true)
}

这种方法需要自己处理导航栏的布局适配,不如方案一省心,所以优先推荐第一种方案。

简单总结:push跳转的VC处于导航栈中,自带导航栏;而present的模态VC是独立的,要显示导航项必须自己提供导航容器或手动添加导航栏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:26:29