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

SwiftUI自定义UINavigationBar后返回按钮消失,如何手动添加?

问题原因

  • 你在init中设置UINavigationBar.appearance().tintColor = .white,同时导航栏背景色也设置为了白色,系统自动生成的返回按钮默认会用tintColor渲染,所以和背景同色导致看不见,并不是返回按钮没有生成。
  • 你提供的示例代码存在语法错误:NavigationLink的destination参数直接嵌套了另一个NavigationLink,导航栈结构异常也会干扰返回按钮的渲染逻辑。

修复方案

方案1:恢复默认返回按钮显示

修改导航栏tintColor为和背景有对比度的颜色,同时修正导航结构即可看到默认返回按钮,示例代码如下:

struct ContentView: View {

    init() {
        let coloredAppearance = UINavigationBarAppearance()
        coloredAppearance.configureWithOpaqueBackground()
        coloredAppearance.backgroundColor = .white
        coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor.black]
        coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.black]
        
        UINavigationBar.appearance().standardAppearance = coloredAppearance
        UINavigationBar.appearance().compactAppearance = coloredAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
        
        // 把tintColor改成黑色,和白色背景形成对比,默认返回按钮就会显示
        UINavigationBar.appearance().tintColor = .black
    }
    
    var body: some View {
        NavigationView {
            NavigationLink {
                // 二级页面内容单独写,不要嵌套NavigationLink
                SecondView()
            } label: {
                Text("Continue")
            }
            .navigationTitle("Nav Title 1")
            .navigationBarTitleDisplayMode(.inline)
        }
    }
}

// 单独定义二级页面
struct SecondView: View {
    var body: some View {
        NavigationLink {
            Color.purple
                .navigationTitle("Nav Title 3")
        } label: {
            Text("Continue")
        }
        .navigationTitle("Nav Title 2")
        .navigationBarTitleDisplayMode(.inline)
    }
}

方案2:手动添加自定义返回按钮

如果你需要完全自定义返回按钮的样式,先隐藏系统默认返回按钮,再通过toolbar自定义即可,示例如下:

struct CustomBackView: View {
    // 获取页面 dismiss 方法实现返回
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        Color.purple
            .navigationTitle("自定义返回页")
            .navigationBarTitleDisplayMode(.inline)
            // 隐藏系统默认返回按钮
            .navigationBarBackButtonHidden(true)
            // 自定义工具栏内容
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button {
                        dismiss()
                    } label: {
                        // 可以自定义样式,比如文字+图标
                        HStack {
                            Image(systemName: "chevron.left")
                            Text("返回")
                        }
                    }
                }
            }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:36:03