简体   繁体   中英

How to change selected date color of UIDatePicker programmatically - Swift 4?

I have created UIDatePicker programatically and added to UITableViewCell . Everything works fine but date color not getting changed even after apply tintColor .

My implementation is:

   var startDatePicker: UIDatePicker = {
    let datePicker = UIDatePicker()
    datePicker.timeZone = NSTimeZone.local
    datePicker.backgroundColor = UIColor.clear
    datePicker.layer.cornerRadius = 5.0
    datePicker.datePickerMode = .date
    datePicker.maximumDate = Date()
    datePicker.isHidden = true
    datePicker.tintColor = UIColor.white
    datePicker.tag = 0
    datePicker.addTarget(self, action: #selector(datePickerValueChanged(datePicker:)), for: .valueChanged)
    return datePicker
}()

I want to show in white color but its showing in default black color . Refer screenshot also.

在此处输入图片说明

Referred this answer.

Apple Documentation says:

The appearance of UIDatePicker is not customizable. You should integrate date pickers in your layout using Auto Layout. Although date pickers can be resized, they should be used at their intrinsic content size. Apple Doc

But then also if you want to customize text color, there is a way to achieve this using private API as below:

datePicker.setValue(UIColor.whiteColor(), forKeyPath: "textColor")

however, private API that could stop working or even cause a crash in any future iOS update.

Then the stable solution would be creating your own Date Picker using UIPickerView and while using that you can customize text color like:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let attributedString = NSAttributedString(string: pickerData[row], attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
    return attributedString
}

After all, I found the way to do by using private API KVC itself ( ViruMax's ans):

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

But I observed, If we implement UIDatePicker using closure then above API must have to assign both closure instance of UIDatePicker as well as outer instance of UIDatePicker. Then only its working.

eg Outer instance of UIDatePicker (startDatePicker) also need to set below KVC.

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

Ans yes it works for Swift 4.

Refer updated screenshot :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM