如何修改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实现通用需求
- iOS 15及以上版本,可直接给对应action实例设置
内容的提问来源于stack exchange,提问作者Bhanu Kashyap
相关产品推荐
相关产品推荐

