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

如何在导航栏内显示iPadOS 18新Tab Bar?

iOS 18 顶部 Tab Bar 与导航栏整合实现方案

针对你遇到的「UITabBarController嵌套在UINavigationController中,顶部TabBar与导航栏重复占用空间、标题重复」的问题,推荐通过自定义导航栏标题视图+隐藏原生TabBar的方式实现需求,具体步骤如下:

1. 清理原生控件的冗余内容

首先隐藏系统导航栏的默认标题,同时清空TabBarItem的标题,避免重复显示:

override func viewDidLoad() {
    super.viewDidLoad()
    
    // 清空导航栏默认标题
    navigationItem.title = ""
    
    // 清空所有TabBarItem的标题
    tabBar.items?.forEach { $0.title = "" }
}

2. 自定义导航栏中间的Tab切换控件

用UISegmentedControl模拟iOS18顶部TabBar的切换逻辑,将其设置为导航栏的titleView,同时关联到UITabBarController的选中索引:

override func viewDidLoad() {
    super.viewDidLoad()
    
    // (接上一步的代码)
    
    // 创建与Tab数量对应的分段控件
    let tabTitles = ["首页", "发现", "我的"] // 替换为你的Tab实际标题
    let tabSegment = UISegmentedControl(items: tabTitles)
    
    // 初始化选中状态与当前Tab一致
    tabSegment.selectedSegmentIndex = selectedIndex
    
    // 设置切换事件
    tabSegment.addTarget(self, action: #selector(onTabSegmentChanged(_:)), for: .valueChanged)
    
    // 自定义样式(贴近iOS18原生TabBar风格)
    tabSegment.selectedSegmentTintColor = .systemBlue
    tabSegment.setTitleTextAttributes([.foregroundColor: UIColor.systemBlue], for: .selected)
    tabSegment.setTitleTextAttributes([.foregroundColor: UIColor.secondaryLabel], for: .normal)
    
    // 将分段控件设置为导航栏标题视图
    navigationItem.titleView = tabSegment
    
    // 隐藏原生TabBar
    tabBar.isHidden = true
}

// 处理Tab切换事件
@objc private func onTabSegmentChanged(_ sender: UISegmentedControl) {
    selectedIndex = sender.selectedSegmentIndex
}

3. 保持导航栏左右按钮正常显示

由于仅替换了导航栏的titleView,左侧返回按钮、右侧自定义按钮的原有逻辑不受影响,无需额外修改。

注意事项

  • 确保UITabBarController的所有子ViewController未单独设置navigationItem.title,避免出现额外标题
  • 分段控件的选项数量必须与TabBar的Item数量完全匹配
  • 若需要更贴近系统原生顶部TabBar的交互细节(如滑动切换),可结合UIPageViewController或手势识别补充实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 23:31:10