首页 > 解决方案 > 在 iOS 12 的 UIDatePicker 中自定义背景和文本颜色

问题描述

在以前的 iOS 版本中,我可以使用以下内容更改文本和背景颜色:

let datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.date
datePicker.setValue(UIColor.white, forKey: "textColor")
datePicker.backgroundColor = UIColor.black.withAlphaComponent(0.6)

这在 Xcode 10/iOS 12 中不再有效。日期选择器以其默认颜色显示。有没有人找到在 iOS 12 中自定义文本和背景颜色的解决方案?

标签: uikituidatepickerxcode10ios12

解决方案


在我设置它们和显示视图之间似乎有一些东西正在重置这些值。我能够通过子类UIDatePicker化和设置值来解决这个问题layoutSubviews()。可能有一个更高效的地方来设置颜色,但现在这对我有用。

class DatePicker: UIDatePicker {
    override func layoutSubviews() {
        super.layoutSubviews()

        backgroundColor = UIColor.black.withAlphaComponent(0.6)
        setValue(false, forKey: "highlightsToday")
        setValue(UIColor.white, forKey: "textColor")
    }
}

推荐阅读