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

Swift中如何修改rightBarButtonItem的文字颜色?

解决导航栏右侧按钮文字颜色修改无效的问题

以下是几种可行的解决思路,按优先级尝试:

1. 确认代码执行时机

确保设置tintColor的代码在导航栏初始化完成后执行,比如放在viewWillAppear或viewDidLoad中:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.navigationItem.rightBarButtonItem?.tintColor = .black
}

2. 检查导航栏全局样式设置

如果项目中设置了导航栏的全局tintColor,会覆盖单个按钮的设置。可以先调整全局样式,再单独设置按钮:

// 若无需全局统一颜色,可先重置导航栏 tintColor
navigationController?.navigationBar.tintColor = .black
// 或直接单独指定按钮颜色
self.navigationItem.rightBarButtonItem?.tintColor = .black

3. 针对自定义按钮的处理

如果右侧按钮是通过自定义UIButton作为customView创建的,直接修改tintColor无效,需要设置按钮的titleColor:

let cancelButton = UIButton(type: .system)
cancelButton.setTitle("取消", for: .normal)
cancelButton.setTitleColor(.black, for: .normal)
cancelButton.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: cancelButton)

4. 检查按钮的style设置

如果创建按钮时使用了.done这类系统特定style,可能会继承默认样式,改为.plain后再设置颜色:

let rightButton = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancelAction))
rightButton.tintColor = .black
self.navigationItem.rightBarButtonItem = rightButton

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 20:54:56