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

导航控制器为何存在边距?如何消除导航栏与安全区间距并保留标题

解决导航栏与安全区间距问题的方案

UIKit 场景

方式一:隐藏系统导航栏,自定义标题消除间距

如果要隐藏系统导航栏但保留标题,可通过让视图延伸到顶部安全区,再手动添加标题控件来消除间距:

// 隐藏系统导航栏
navigationController?.setNavigationBarHidden(true, animated: false)
// 允许视图延伸到导航栏原本的区域
edgesForExtendedLayout = .top

// 添加自定义标题Label
let titleLabel = UILabel(frame: CGRect(x: 0, y: view.safeAreaInsets.top, width: view.frame.width, height: 44))
titleLabel.text = "自定义标题"
titleLabel.textAlignment = .center
titleLabel.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
view.addSubview(titleLabel)

方式二:保留系统导航栏,消除多余间距

如果不想隐藏导航栏,可通过修改导航栏外观让其贴合安全区:

// 清空导航栏背景图和阴影图,设置为透明
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true

// 调整导航栏标题位置,避免偏移
navigationController?.navigationBar.titleTextAttributes = [
    NSAttributedString.Key.foregroundColor: UIColor.black,
    NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17, weight: .semibold)
]

SwiftUI 场景

用 NavigationStack(iOS 16+)

通过隐藏导航栏背景、让内容延伸到安全区,同时自定义标题:

NavigationStack {
    YourCustomContentView()
        .toolbar {
            ToolbarItem(placement: .principal) {
                Text("页面标题")
                    .font(.headline)
            }
        }
        .toolbarBackground(.hidden, for: .navigationBar) // 隐藏导航栏背景
        .edgesIgnoringSafeArea(.top) // 让内容延伸到顶部安全区
}

用 NavigationView(iOS 15及以下)

NavigationView {
    YourCustomContentView()
        .navigationBarTitle("页面标题", displayMode: .inline)
        .navigationBarBackground(.hidden)
        .edgesIgnoringSafeArea(.top)
}

关键说明

出现这类间距通常是因为系统默认的导航栏半透明特性,或者视图未设置延伸到安全区上方导致的。以上方案通过调整视图布局、修改导航栏样式,既能保留标题,又能消除多余间距。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:22:43