[英]How to Change UIDatePicker Selected Color and Font Without Being Hacky in Swift?
[英]How to change selected date color of UIDatePicker programmatically - Swift 4?
我已經以編程方式創建了UIDatePicker
並將其添加到UITableViewCell
。 一切正常,但即使應用tintColor
之后,日期顏色也不會更改。
我的實現是:
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
}()
我想以白色為主色調 ,但其在默認的黑色 配色顯出顯現。 另請參閱屏幕截圖。
引用了這個答案。
蘋果文檔說:
UIDatePicker的外觀不可自定義。 您應該使用自動版式將日期選擇器集成到版式中。 盡管可以調整日期選擇器的大小,但應按其固有的內容大小使用它們。 蘋果文件
但是,如果您想自定義文本顏色,則可以使用私有API實現此目的,如下所示:
datePicker.setValue(UIColor.whiteColor(), forKeyPath: "textColor")
但是,私有API可能會停止工作,甚至在將來的任何iOS更新中導致崩潰。
然后,穩定的解決方案是使用UIPickerView
創建自己的日期選擇器,並在使用時可以自定義文本顏色,例如:
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let attributedString = NSAttributedString(string: pickerData[row], attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
return attributedString
}
畢竟,我找到了使用私有API KVC本身的方法( ViruMax的 ans):
datePicker.setValue(UIColor.white, forKeyPath: "textColor")
但是我觀察到,如果我們使用閉包實現UIDatePicker,則上述API必須同時分配UIDatePicker的閉包實例和UIDatePicker的外部實例。 然后只有它的工作。
例如, UIDatePicker
外部實例(startDatePicker)也需要設置在KVC以下。
startDatePicker.setValue(UIColor.white, forKeyPath: "textColor")
回答是的,它適用於Swift 4。
請參閱更新的屏幕截圖:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.