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

Swift修改App导航栏返回按钮的颜色与图标

自定义导航栏返回按钮并修改图标颜色(保留侧滑返回)

我需要实现自定义样式的导航栏返回按钮,同时保留系统侧滑返回功能。已知官方暂未提供直接支持,但可以通过以下方案实现,且能明确区分按钮图标与文字:

已尝试的三种基础实现方式

1. 隐藏标准导航栏背景及阴影

// 配置UINavigationBarAppearance
let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground() // 透明背景
appearance.shadowColor = nil // 移除阴影
appearance.backgroundColor = .clear // 清空背景色

// 全局应用样式
UINavigationBar.appearance().standardAppearance = appearance

2. 替换返回按钮默认图标

// 配置UINavigationBarAppearance
let appearance = UINavigationBarAppearance()

// 创建自定义返回按钮图标(使用Apple提供的SF Symbols)
let backImage = UIImage(systemName: "chevron.backward") // 替换为目标图标名称
appearance.setBackIndicatorImage(backImage, transitionMaskImage: backImage)
        
// 全局应用样式
UINavigationBar.appearance().standardAppearance = appearance

3. 自定义返回按钮文字样式

// 自定义返回按钮文字外观
let backButtonAppearance = UIBarButtonItemAppearance(style: .plain)
backButtonAppearance.normal.titleTextAttributes = [
    .font: UIFont.systemFont(ofSize: 16, weight: .medium),
    .foregroundColor: UIColor.black // 文字颜色
]
appearance.backButtonAppearance = backButtonAppearance
        
// 全局应用样式
UINavigationBar.appearance().standardAppearance = appearance

整合后的基础代码示例

struct StartupPage2: View {
    init() {
        // 配置UINavigationBarAppearance
        let appearance = UINavigationBarAppearance()
        appearance.configureWithTransparentBackground() // 透明背景
        appearance.shadowColor = nil // 移除阴影
        appearance.backgroundColor = .clear // 清空背景色

        // 自定义返回按钮文字样式
        let backButtonAppearance = UIBarButtonItemAppearance(style: .plain)
        backButtonAppearance.normal.titleTextAttributes = [
            .font: UIFont.systemFont(ofSize: 16, weight: .medium), // 文字字体
            .foregroundColor: UIColor.black // 文字颜色
        ]
        appearance.backButtonAppearance = backButtonAppearance

        // 设置自定义返回图标
        let backImage = UIImage(systemName: "chevron.backward")
        appearance.setBackIndicatorImage(backImage, transitionMaskImage: backImage)
            
        // 全局应用样式
        UINavigationBar.appearance().standardAppearance = appearance
    }
}

修改返回图标颜色的解决方案

要修改返回图标的颜色,需要通过UIImage的withTintColor方法给图标添加指定颜色,同时确保过渡遮罩图也使用相同处理后的图片,代码调整如下:

// 创建带指定颜色的返回图标
let backImage = UIImage(systemName: "chevron.backward")?.withTintColor(.black, renderingMode: .alwaysOriginal)
appearance.setBackIndicatorImage(backImage, transitionMaskImage: backImage)

关键在于使用withTintColor(_:renderingMode:)并指定renderingMode为.alwaysOriginal,这样能保证图标的颜色不会被导航栏的全局色调覆盖,从而精准设置自定义颜色。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 08:03:14