Change UIDatePicker TextColor in iOS10

Tags: ios swift
Question!

I had a method of changing the UIDatePicker's text color on versions of iOS before 10, but with iOS10 those solutions no longer appear to work. How could I restore the ability to change the textColor for a UIDatePicker?

   if #available(iOS 10.0, *) {
        //Not sure of a way to do something similar here.
   } else {
        //The following lines change the textColor of UIDatePicker to white in iOS9 and older.
        self.setValue(UIColor.white, forKey: "textColor")
        self.sendAction(Selector("setHighlightsToday:"), to: nil, for: nil) 
   }


Answers

The text colour seems to reset on opening the picker.

I was able to get the text colour to change by using:

setValue(UIColor.white, forKey: "textColor")

after the date picker had appeared on screen. Do it soon enough after and its not noticeable.

I'm not sure how your using your picker, but I had mine set as the input view for a textfield, so was able to use the textfield delegate:

func textFieldDidBeginEditing(textField: UITextField)

to know when the picker had been opened.

I did need to dispatch it with a small delay to take effect correctly.

Update

Instead of using the private textColor property of UIDatePicker, this can be better achieved by using appearances and the public textColor property of UILabel.

UILabel.appearanceWhenContainedInInstancesOfClasses([UIDatePicker.self]).textColor = UIColor.whiteColor()

It still needs to be called after the date picker has been displayed to work.



The code you're using is setting a private property of the UIDatePicker. That's the danger of using a private property. There's no guarantee that it will work in the next OS version.

If Apple detected what you were doing they would have rejected your app.

Unless there is a public interface for doing this, you may be out of luck. (And I'm not aware of a public interface for changing the text color of a date picker.)

By : Duncan C


Nothing seems to have changed because I am able to achieve it even using Swift 3 as shown below.

import UIKit

class ViewController: UIViewController
{
    override func viewDidLoad()
    {
        super.viewDidLoad()

        let temp: UIDatePicker = UIDatePicker(frame: self.view.frame)
        temp.setValue(UIColor.purple, forKey: "textColor")

        view.addSubview(temp)
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }
}


This video can help you solving your question :)
By: admin