How to change the text color of a compact UIDatePicker

I have a compact date picker that has nearly unreadable text when the app is light mode. datepicker with dark text Is there a way to change the color of it?

Note, I've tried the following:

Upvotes: 2

Views: 1412

Answers (2)

giacoder
giacoder

Reputation: 980

I found a solution which is more like a hack. I've spent a lot of time, hope it will be useful for somebody. Here is a code:

class MyCompactDatePicker: UIDatePicker {
    
    var textColorToSet = UIColor.magenta //default color, can be set from outside
    
    private var lblDate: UILabel?
    private var lblTime: UILabel?
    
    private var actionId: UIAction.Identifier?

    override func draw(_ rect: CGRect) {
        if preferredDatePickerStyle != .compact {
            preferredDatePickerStyle = .compact
        }
        
        super.draw(rect)
        
        findLabels()
        colorLabels()
        
        if actionId == nil {
            let action = UIAction(title: "colorLabels", handler: { [weak self] _ in
                DispatchQueue.main.async { //without this dispatch delay color will not be ours when switching between date and time
                    self?.colorLabels()
                }
            })
            actionId = action.identifier
            
            addAction(action, for: .allEvents)
        }
    }
    
    private func colorLabels() {
        lblDate?.textColor = textColorToSet
        lblTime?.textColor = textColorToSet
    }
    
    private func findLabels() {
       if lblDate == nil || lblTime == nil {
            var n = 0
            recursFindLabels(v: self, number: &n)
       }
    }
    
    private func recursFindLabels(v: UIView, number: inout Int) {
        if let lbl = v as? UILabel {
            switch number {
            case 0:
                lblDate = lbl
            case 1:
                lblTime = lbl
            default:
                return
            }
        
            number += 1
            if number > 1 {  //only first 2 labels are Date and Time labels
                return
            }
        }
        
        for sv in v.subviews {
            recursFindLabels(v: sv, number: &number)
        }
    }
}

and set from ViewController

class ViewController: UIViewController {

    @IBOutlet weak var datePicker: MyCompactDatePicker!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        datePicker.textColorToSet = .green
    }
}

The date and time will be in green.

Note: the tintColor will also be overridden by green but it's not a big deal.

Upvotes: 1

It looks like you can't set a custom color for the date picker text, but you can force the date picker to always be in dark mode

datePicker.overrideUserInterfaceStyle = .dark

Upvotes: 4

Related Questions