Reputation: 7459
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.
Upvotes: 2
Views: 4554
Reputation: 1218
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
}
Upvotes: 5
Reputation: 7459
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.
e.g 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 :
Upvotes: 3