You need to enable JavaScript to run this app. 如何修改UIAlertAction与UIAlertActionSheet的标题颜色
优惠活动
大模型
产品
解决方案
定价
更多

如何修改UIAlertAction与UIAlertActionSheet的标题颜色

问题成因

view.tintColor 的作用范围仅覆盖UIAlertController内所有可交互的UIAlertAction文字颜色,静态展示的标题、提示文本不属于tintColor的管控范围,因此仅设置该属性无法修改标题颜色。

正确实现方式

当前系统中没有独立的UIAlertActionSheet类,所有弹窗类交互都通过UIAlertController实现,通过preferredStyle参数区分是居中Alert弹窗还是底部ActionSheet面板。修改标题、副标题颜色无需调用私有API,直接使用官方提供的富文本配置属性即可:

  • 自定义主标题颜色与样式:为UIAlertController的attributedTitle属性赋值携带颜色、字体等配置的富文本对象
  • 自定义副标题(Message)颜色与样式:为attributedMessage属性赋值对应配置的富文本对象
  • 统一调整动作按钮文字颜色:设置view.tintColor即可,该配置与富文本设置互不冲突

可直接参考的实现代码:

// 初始化动作面板样式的弹窗
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

// 配置标题的样式:红色、17号粗体
let titleText = "请选择操作方式"
let titleAttrs: [NSAttributedString.Key: Any] = [
    .foregroundColor: UIColor.systemRed,
    .font: UIFont.boldSystemFont(ofSize: 17)
]
alertController.attributedTitle = NSAttributedString(string: titleText, attributes: titleAttrs)

// 配置副标题样式:深灰色、13号常规字体
let messageText = "选择后将自动保存当前编辑内容"
let messageAttrs: [NSAttributedString.Key: Any] = [
    .foregroundColor: UIColor.darkGray,
    .font: UIFont.systemFont(ofSize: 13)
]
alertController.attributedMessage = NSAttributedString(string: messageText, attributes: messageAttrs)

// 统一设置所有动作按钮的文字颜色
alertController.view.tintColor = .systemBlue

// 添加动作按钮
alertController.addAction(UIAlertAction(title: "拍照上传", style: .default, handler: { _ in
    // 对应业务逻辑
}))
alertController.addAction(UIAlertAction(title: "从相册选择", style: .default, handler: { _ in
    // 对应业务逻辑
}))

// 单独设置删除动作的文字颜色(iOS 15+)
let deleteAction = UIAlertAction(title: "删除草稿", style: .destructive, handler: { _ in
    // 对应业务逻辑
})
if #available(iOS 15.0, *) {
    deleteAction.titleTextColor = .systemRed
}
alertController.addAction(deleteAction)

alertController.addAction(UIAlertAction(title: "取消", style: .cancel))

// 弹出弹窗
present(alertController, animated: true)
版本适配说明
  • attributedTitle、attributedMessage配置从iOS 6开始就被官方支持,无App Store审核风险
  • 如需单独修改某一个UIAlertAction的文字颜色:
    • iOS 15及以上版本,可直接给对应action实例设置titleTextColor属性自定义颜色,无需调整全局tintColor
    • 更低版本的系统没有开放单个action颜色的单独配置接口,只能通过系统内置样式(如.destructive默认显示红色)搭配全局tintColor实现通用需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.15 02:45:06