如何修改紧凑型日期UIPickerView的强调色与当前日期未选状态颜色
紧凑型UIDatePicker日历弹窗颜色修改方案
一、修改弹窗蓝色强调色
你之前在Storyboard修改tintColor仅生效于顶部显示的日期文本,是因为日历弹窗属于系统单独渲染的弹出层,需要额外配置:
- 方案1:全局修改(适配所有iOS14+版本)
在AppDelegate或SceneDelegate的启动方法中添加全局外观配置,所有系统组件的强调色都会同步修改:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UIView.appearance().tintColor = .systemRed // 替换为你需要的颜色 return true }
- 方案2:仅修改当前DatePicker的弹窗(无全局影响,iOS16+推荐)
通过iOS16新增的公开API直接访问弹窗内的UICalendarView配置:
@IBOutlet weak var datePicker: UIDatePicker! override func viewDidLoad() { super.viewDidLoad() if #available(iOS 16.0, *) { datePicker.tintColor = .systemPurple // 替换为目标强调色 } }
- 方案3:iOS14/15兼容方案
通过运行时获取弹出的弹窗控制器修改tint,注意该方案使用了私有属性,存在小概率审核风险:
// 在datePicker添加值变化监听或者弹出前调用 if let popup = datePicker.value(forKey: "presentedViewController") as? UIViewController { popup.view.tintColor = .systemPurple }
二、修改未选中状态的日期文本颜色
- iOS16+公开API方案:
直接配置UICalendarView的文本属性即可,无需遍历私有视图:
if #available(iOS 16.0, *) { guard let calendarView = datePicker.calendarView else { return } // 修改普通日期未选中的文本颜色 calendarView.dayTextAttributes = [.foregroundColor: UIColor.gray] // 修改今天未选中的文本颜色 calendarView.todayTextAttributes = [.foregroundColor: UIColor.orange] // 可选:修改周末日期的文本颜色 calendarView.weekendTextAttributes = [.foregroundColor: UIColor.lightGray] }
- iOS14/15兼容方案:
遍历弹窗内的子视图修改文本颜色,同样存在审核风险:
// 先添加UIView扩展获取所有子视图 extension UIView { var allSubviews: [UIView] { subviews + subviews.flatMap({ $0.allSubviews }) } } // 弹窗弹出后调用 if let popup = datePicker.value(forKey: "presentedViewController") as? UIViewController { popup.view.allSubviews.forEach { subview in if let label = subview as? UILabel, label.textColor == .black { label.textColor = .gray // 替换为目标颜色 } } }
内容的提问来源于stack exchange,提问作者dem
相关产品推荐
相关产品推荐

