You need to enable JavaScript to run this app. iOS全局导航栏、Alert及ActionSheet标题变白,如何全局统一设置?
优惠活动
大模型
产品
解决方案
定价
更多

iOS全局导航栏、Alert及ActionSheet标题变白,如何全局统一设置?

解决iOS项目全局弹窗、导航栏标题变白问题

遇到的问题

  • 全项目范围内的导航栏、普通弹窗、底部Action Sheet弹窗的标题文字默认显示为白色,和弹窗/导航栏的浅色背景对比度极低,基本无法阅读
  • 此前找到的所有方案都仅支持给单个弹窗单独设置标题颜色,每创建一个弹窗就要重复写一遍配置代码,无法实现全局统一的样式设置,冗余度极高

效果截图1
效果截图2

现有业务代码参考

func inliseAlert(_ imageSelection: Int, _ VC: UIViewController, _ success: @escaping ImageSelectionCompletion) {
    //Change color of selection overlay to white
    viewController = VC
    numberOfImage = imageSelection
    self.success = success
    let imageSourceAlert = UIAlertController(title: "Choose Image", message: "", preferredStyle: UIAlertController.Style.actionSheet)
   
    let camera = UIAlertAction(title: "Camera", style: .default) { [weak self](action: UIAlertAction) in
        DispatchQueue.main.async {
            self?.openCamera()
        }
    }
   
    let gallery = UIAlertAction(title: "Gallery", style: .default) { [weak self] (action: UIAlertAction) in
        guard let self = self else { return }
        DispatchQueue.main.async {
            self.openGallery()
        }
    }
   
    let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
    imageSourceAlert.addAction(camera)
    imageSourceAlert.addAction(gallery)
    imageSourceAlert.addAction(cancelAction)
   
    viewController?.present(imageSourceAlert, animated: true, completion: nil)
}

全局统一配置实现方法

完全不需要逐弹窗单独写样式配置,直接在App启动的初始化流程(比如AppDelegate的didFinishLaunchingWithOptions方法)中添加UIAppearance全局配置,即可一次性覆盖所有弹窗、导航栏的默认样式:

  • 全局设置所有UIAlertController(包含普通Alert、底部Action Sheet)的标题文字样式
// 统一设置弹窗标题为黑色、匹配系统默认字体大小
let alertTitleAttrs: [NSAttributedString.Key: Any] = [
    .foregroundColor: UIColor.black,
    .font: UIFont.systemFont(ofSize: 16, weight: .medium)
]
UIAlertController.appearance().setValue(alertTitleAttrs, forKey: "attributedTitle")
  • 全局设置导航栏的标题、按钮文字样式
// 导航栏全局配置
let navBar = UINavigationBar.appearance()
navBar.titleTextAttributes = [.foregroundColor: UIColor.black]
navBar.tintColor = .systemBlue

注意事项

  • 以上代码仅需在App启动时执行一次,后续所有新创建的弹窗、导航栏组件都会自动应用配置的样式,不需要在业务代码中重复写设置逻辑
  • 若部分弹窗需要单独自定义标题样式,只需要在对应弹窗创建完成后单独修改自身的attributedTitle属性即可,不会和全局配置冲突
  • 该配置对iOS13及以上系统版本全适配,不需要针对不同设备尺寸做额外判断

内容的提问来源于stack exchange,提问作者Gurpreet Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 12:24:04