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

如何将工具栏/导航栏中UIBarButtonItem的文本设置为粗体?

给UIBarButtonItem设置粗体的简便方法

嘿,这个需求我之前做项目时刚好碰到过,其实有两种很实用的方法,不用绕弯路:

方法一:单独给某个UIBarButtonItem设置粗体

直接用NSAttributedString来配置,这是最直接的方式,能精准控制单个按钮:

// 创建适配系统的粗体字体,尺寸可按需调整
let boldFont = UIFont.boldSystemFont(ofSize: 16)
// 构建富文本属性字典,还能顺便设置文字颜色等样式
let attributes: [NSAttributedString.Key: Any] = [
    .font: boldFont,
    .foregroundColor: UIColor.systemBlue // 可选配置
]
// 创建带样式的富文本标题
let attributedTitle = NSAttributedString(string: "保存", attributes: attributes)
// 给目标UIBarButtonItem设置富文本标题
let barButton = UIBarButtonItem()
barButton.setAttributedTitle(attributedTitle, for: .normal)

这种方法还支持针对不同状态(比如.highlighted、.disabled)设置不同的粗体样式,只需要修改setAttributedTitle的第二个状态参数即可。

方法二:全局统一设置所有UIBarButtonItem的粗体

如果你的App里所有导航栏按钮都需要粗体,用UIAppearance全局配置更省心,不用逐个按钮写代码:

// 在App启动时(比如AppDelegate或SceneDelegate的初始化方法)设置
UIBarButtonItem.appearance().setTitleTextAttributes([
    .font: UIFont.boldSystemFont(ofSize: 16)
], for: .normal)

// 也可以给禁用状态单独配置样式
UIBarButtonItem.appearance().setTitleTextAttributes([
    .font: UIFont.boldSystemFont(ofSize: 16),
    .foregroundColor: UIColor.systemGray
], for: .disabled)

关于你提到的Helvetica-Bold的小提醒

你说的用UIFont(name: "Helvetica-Bold", size: 12)的方式确实可行,但更推荐用UIFont.boldSystemFont(ofSize:)——因为iOS不同版本的默认系统字体可能会变化(比如iOS13后用San Francisco替代了Helvetica),系统提供的粗体方法会自动适配当前系统的默认字体,兼容性更好。

内容的提问来源于stack exchange,提问作者Adam S.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:49:49