如何以编程方式更改UIDatePicker的选定日期颜色 - Swift 4?

时间:2018-06-12 03:06:42

标签: ios swift4 uidatepicker

我以编程方式创建了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
}()

我希望以白色显示,但其显示为默认黑色 颜色。请参阅截图。

enter image description here

2 个答案:

答案 0 :(得分:1)

提到this回答。

Apple文档说:

  

UIDatePicker的外观无法自定义。你应该   使用自动布局将日期选择器集成到您的布局中。虽然约会   拾取器可以调整大小,应该根据其内在内容使用   尺寸。 Apple Doc

但是如果你想自定义文本颜色,有一种方法可以使用私有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
}

答案 1 :(得分:1)

毕竟,我找到了使用私有API KVC本身(ViruMax's ans)的方法:

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

但是我观察到,如果我们使用 closure 实现UIDatePicker,那么上面的API必须分配UIDatePicker的闭包实例和UIDatePicker的外部实例。然后只有它的工作。

例如UIDatePicker(startDatePicker)的外部实例也需要设置在KVC以下。

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

答案是的,它适用于Swift 4.

参考更新的截图:

enter image description here