Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize background and text color in UIDatePicker in iOS 12

In previous iOS versions, I was able to change the text and background colors using the something like the following:

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

This is no longer working in Xcode 10/iOS 12. The date picker is displayed with its default colors. Has anyone found a solution for customizing the text and background colors in iOS 12?

like image 209
Sean Kladek Avatar asked Oct 25 '18 16:10

Sean Kladek


1 Answers

It seems something is resetting those values between when I set them and when the view is displayed. I was able to solve this by subclassing UIDatePicker and setting the values in layoutSubviews(). There may be a more performant place to set the colors, but this is working for me for now.

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

        backgroundColor = UIColor.black.withAlphaComponent(0.6)
        setValue(false, forKey: "highlightsToday")
        setValue(UIColor.white, forKey: "textColor")
    }
}
like image 173
Sean Kladek Avatar answered Nov 04 '22 09:11

Sean Kladek