Change UIDatePicker font color?

Viewed 46931

All I want to do is change the font color of the UIDatePicker. I've researched other questions but they're all involving changing other properties and customizing the entire look. All I want to do is just change the font color from black to white. I find it hard to believe that I can't do such a seemingly simple task. And why wouldn't the tint color affect it? Does it even do anything?

17 Answers

I stumbled upon a surprisingly clean solution using UIAppearance, without using any KVC, swizzling, or otherwise private API. I found that attempting to set the textColor via UIAppearance for any UILabel within a UIDatePicker had no affect, but a custom appearance property that simply called the regular textColor setter worked just fine.

// Implement a custom appearance property via a UILabel category
@interface UILabel (PickerLabelTextColor)

@property (nonatomic, strong) UIColor * textColorWorkaround UI_APPEARANCE_SELECTOR;

@end

@implementation UILabel (PickerLabelTextColor)

- (UIColor *)textColorWorkaround {
    return self.textColor;
}

- (void)setTextColorWorkaround:(UIColor *)textColor {
    self.textColor = textColor;
}

@end

And then use as follows:

UILabel *pickerLabelProxy = [UILabel appearanceWhenContainedInInstancesOfClasses:@[UIDatePicker.class]];
pickerLabelProxy.textColorWorkaround = UIColor.lightGrayColor;

Swift Version

UILabel extension:

extension UILabel {
    @objc dynamic var textColorWorkaround: UIColor? {
        get {
            return textColor
        }
        set {
            textColor = newValue
        }
    }
}

Appearance proxy use:

let pickerLabelProxy = UILabel.appearance(whenContainedInInstancesOf: [UIDatePicker.self])
pickerLabelProxy.textColorWorkaround = UIColor.lightGray

It didn't work until textColor was set inside layoutSubviews()

override func layoutSubviews() {
    super.layoutSubviews()
    datePicker.backgroundColor = .black
    datePicker.setValue(.white, forKeyPath: "textColor")
}

Just use datePicker.tintColor = .red or any other color you want.

[my_date_picker setValue:[UIColor whiteColor] forKey:@"textColor"];

it seems don't work on ios 13 or later, you can set overrideUserInterfaceStyle property for UIDatePicker to determin it shows white color or black.

Related