Sun*_*rge 2 uidatepicker ios swift4
我已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
}()
Run Code Online (Sandbox Code Playgroud)
我想以白色显示,但它以默认黑色 显示。另请参阅屏幕截图。
参考了这个答案。
苹果文档说:
UIDatePicker 的外观不可自定义。您应该使用自动布局将日期选择器集成到布局中。尽管可以调整日期选择器的大小,但应按其固有内容大小使用它们。苹果文档
但如果你想自定义文本颜色,有一种方法可以使用私有 API 来实现,如下所示:
datePicker.setValue(UIColor.whiteColor(), forKeyPath: "textColor")
Run Code Online (Sandbox Code Playgroud)
然而,私有 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
}
Run Code Online (Sandbox Code Playgroud)