我的一个ViewControllers中有一个UIDatePicker。如您所见,背景很暗。
我已经设法改变的是文本颜色为白色。我无法改变的是所选日期上下两行的颜色。它始终保持默认的深灰色。有没有人有剪切代码来实现这些线的着色?
首先,Apple文档说,关于Date Pickers
,“你不能自定义日期选择器的外观。”
话虽这么说,以下代码正是您所需要的。我知道它不是最优雅的代码片段,但在这里它是
datePicker.subviews[0].subviews[1].backgroundColor = UIColor.redColor()
datePicker.subviews[0].subviews[2].backgroundColor = UIColor.redColor()
UIDatePicker有一个子视图UIDatePickerView,它有3个子视图,后者中的2个是指示选择行的两行。
huniser_suraj答案是正确的,只是使用额外的检查以便将来的更改,这就是我如何使用它,分别用于UIPickerView和UIDatePicker:
for subview in self.picker.subviews {
if subview.frame.height == 1 {
subview.backgroundColor = UIColor.whiteColor()
}
}
if let pickerView = self.datePicker.subviews.first {
for subview in pickerView.subviews {
if subview.frame.height == 1 {
subview.backgroundColor = UIColor.whiteColor()
}
}
}
iOS 10更新
从iOS 10开始,这不再起作用,如某些评论中所述,即查找子视图并获取它们可行,但设置背景颜色不再起作用。我为此做了另一个肮脏的解决方案,我正在设置边框颜色的边框。
for subview in self.picker.subviews {
if subview.frame.height <= 5 {
subview.backgroundColor = UIColor.white
subview.tintColor = UIColor.white
subview.layer.borderColor = UIColor.white.cgColor
subview.layer.borderWidth = 0.5 }
}
if let pickerView = self.datePicker.subviews.first {
for subview in pickerView.subviews {
if subview.frame.height <= 5 {
subview.backgroundColor = UIColor.white
subview.tintColor = UIColor.white
subview.layer.borderColor = UIColor.white.cgColor
subview.layer.borderWidth = 0.5
}
}
self.datePicker.setValue(UIColor.white, forKey: "textColor")
}
它可以通过IB以非常简单的方式完成。只需将2个UiView放置为高度= 1,宽度等于UIDatePicker。然后垂直和水平地使用UIDatePicker对中。对于上面一行,将垂直偏移设置为18,将另一个设置为-18。完成!
我不得不更改datePicker的高度约束,而这个@kex代码的cus对我没用。所以我修改了它:(适用于swift 5和iOS 12)
if let _pickerView = self.datePicker.subviews.first {
for _subview in _pickerView.subviews {
if (_subview.backgroundColor != nil) {
_subview.backgroundColor = UIColor.white
_subview.tintColor = UIColor.white
_subview.layer.borderColor = UIColor.white.cgColor
_subview.layer.borderWidth = 1
}
}
}