iKK
iKK

Reputation: 7012

iOS14 - How to change textColor of UIDatePicker in UIKit?

Using iOS14.0.1, Swift5.3, Xcode12.0.1,

I try to change the textColor of a UIDatePicker in iOS14 and using UIKit.

I read here that you need the following method to do so:

let myDatePicker = UIDatePicker()
myDatePicker.tintColor = .white

I also tried the following (but that makes my app crash under iOS14):

myDatePicker.setValue(UIColor.white, forKeyPath: "textColor")

I also tried (but without success either):

UILabel.appearance(whenContainedInInstancesOf: [UIDatePicker.self]).textColor = UIColor.white

In light mode, none of my trials work (as can bee seen in the screenshot-excerpt):

enter image description here

What do I need to do to get the white color text in my UIDatePicker?

Upvotes: 5

Views: 5134

Answers (3)

Fabio
Fabio

Reputation: 5648

Try this, add the extension below:

extension UIDatePicker {

var textColor: UIColor? {
    set {
        setValue(newValue, forKeyPath: "textColor")
    }
    get {
        return value(forKeyPath: "textColor") as? UIColor
    }
  }
}

Now in viewDidLoad call:

myDatePicker.textColor = .yourColor

call it after other picker property, es.:

myDatePicker.preferredDatePickerStyle = .wheels
myDatePicker.addTarget(self, action: #selector(handleDatePicker), for: .valueChanged)
myDatePicker.datePickerMode = .dateAndTime
myDatePicker.timeZone = NSTimeZone.local
myDatePicker.backgroundColor = .black
myDatePicker.setValue(false, forKey: "highlightsToday")
myDatePicker.textColor = .yourColor // here

enter image description here

if you want highlightsToday set the relative picker value to true:

myDatePicker.setValue(true, forKey: "highlightsToday")

and this is the result:

enter image description here

Upvotes: 4

Petter Wang
Petter Wang

Reputation: 31

Yes, It works! However, the proprety preferredDatePickerStyle = .wheels must be set before textColor = .yourColor, or the propetty textColor may never be affected.

Upvotes: 3

mehmett
mehmett

Reputation: 111

I change picker view color using pickerView delegate method. You can add this function with add these delegate methods: UIPickerViewDelegate, UIPickerViewDataSource

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

      // change your picker view textColor etc. in here..
}

Upvotes: 0

Related Questions